二叉搜索应用(2)

1.完全二叉树结点的个数

1.问题:给一个完全二叉树的根节点,返回该二叉树的结点数。

2.步骤:

  1.计算左子树和右子树的高度,记为h1,h2

  2.如果h1=h2,则左子树必满,n+=2^h1-1.计算右子树

  3.如果h1>h2,则右子树比满,n+=2^h2-1,计算左子树

  4.如果h1=0,则结束。

3.实现代码

int count1(TreeNode* root){
    int n=0;
    n++;
    int h1=0;int h2=0;
    TreeNode* current=root->left;
    while(current!=NULL) {
        h1++;
        current=current->left;
    }
    current=root->right;
    while(current!=NULL) {
        h2++;
        current=current->left;
    }

    if(h1==0) return n;//无左右子树

    if(h1==h2){//左子树满,统计右子树
        n+=pow(2,h1)-1;
        n+=count1(root->right);
    }else{//右子树满,统计左子树
        n+=pow(2,h2)-1;
        n+=count1(root->left);
    }
    return n;
}

 

2.快速求幂运算

如pow(3,9)

1.将9写为1001(二进制)

2.计算3,3^2,3^4,3^8,其中3^2=3*3,3^4=3^2*3^2

3.9=1*3+1*3^8

posted @ 2018-05-01 17:19  即便那总是过去  阅读(110)  评论(0编辑  收藏  举报