码迷,mamicode.com
首页 > 其他好文 > 详细

Count Complete Tree Nodes

时间:2016-02-23 00:49:06      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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

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

标签:

原文地址:http://www.cnblogs.com/wxquare/p/5208522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!