LC 222. Count Complete Tree Nodes (二分查找)

link

/**
 * 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;
    }
};
posted @ 2020-11-24 09:02  feibilun  阅读(73)  评论(0编辑  收藏  举报