Count Complete Tree Nodes

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Count Complete Tree Nodes相关的知识,希望对你有一定的参考价值。

题目:计算完全二叉树的节点数目(二分法)

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2hnodes inclusive at the last level h.

c++:

class Solution {
public:
    bool isExistNode(TreeNode *root,int h,int m){
        TreeNode *p = root;
        for(int i=h-2;i>=0;i--){
            if(m & (1<<i)) p = p->right;
            else p=p->left;
        }
        return p != nullptr;
    }
    int countNodes(TreeNode* root) {
        if (root == nullptr)
            return 0;
        int h = 0;
        TreeNode* p = root;
        while (p != nullptr) {
            h++;
            p = p->left;
        }

        int l = 0;
        int r = (1 << (h - 1)) - 1;
        int m;
        while (l <= r) {
            m = l + ((r-l) >> 1);
            if (isExistNode(root, h, m))
                l = m + 1;
            else
                r = m - 1;
        }
        return (1 << (h - 1)) + r;
    }
};

java:

public class Solution {
    public boolean isExistNode(TreeNode root,int h,int m){
        TreeNode p = root;
        for(int i = h-2;i>=0;i--){
            if((m & (1<<i)) != 0) p = p.right;
            else p = p.left;
        }
        return p != null;
        
    }
    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        int h = 0;
        TreeNode p = root;
        while(p != null){
            h++;
            p = p.left;
        }
        
        int l=0;
        int r = (1<<(h-1)) - 1;
        int m;
        while(l<=r){
            m = l+((r-l)>>1);
            if(isExistNode(root,h,m)) l = m+1;
            else r = m-1;
        }
        
        return (1<<(h-1))+r;
        
    }
}

 

以上是关于Count Complete Tree Nodes的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 222. Count Complete Tree Nodes

222. Count Complete Tree Nodes

Count Complete Tree Nodes

Count Complete Tree Nodes

222. Count Complete Tree Nodes

222. Count Complete Tree Nodes