题目:计算完全二叉树的节点数目(二分法)
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; } }