标签:tree node image false roo problems img complete mic bit
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL&& root->right==NULL) return 1;
int level=1;
TreeNode* cur=root->left;
while(cur!=NULL){
level++;
cur=cur->left;
}
int left=getcnt(level-1)+1;
int right=getcnt(level);
while(left<=right){
int mid=(left+right)/2;
if(exists(root,mid,level)){
left=mid+1;
}else{
right=mid-1;
}
}
return right;
}
bool exists(TreeNode* root,int n, int level){
int checkbit=1<<(level-2);
while(checkbit>0){
if(checkbit&n){
if(root->right==NULL) return false;
root=root->right;
}else{
if(root->left==NULL) return false;
root=root->left;
}
checkbit>>=1;
}
return true;
}
int getcnt(int n){
return (1<<n)-1;
}
};
LC 222. Count Complete Tree Nodes (二分查找)
标签:tree node image false roo problems img complete mic bit
原文地址:https://www.cnblogs.com/FEIIEF/p/14028473.html