The number of nodes in a complete binary tree (two sets of two points)

Title
reference The
last layer of the dichotomy, every time chek uses the dichotomy to see if the node exists.

/**
 * 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 getd(TreeNode *root) {
    	int d = 0;
    	while(root->left) {
    		++d;
    		root = root->left;
		}
		return d;
	}
	bool ok(TreeNode *root,int &val,int d) {
		int l = 0,r = (1<<d)-1;
		int mid;
		for(int i = 0;i < d;++i) {
			mid = (l+r)/2;
			if(val <= mid) {
				root = root->left;
				r = mid;
			}else {
				root = root->right;
				l = mid+1;
			}
		}
		return root != nullptr; 
	}
    int countNodes(TreeNode* root) {
    	if(root == nullptr) return 0;
        int d = getd(root);
        int l = 1,r = (1<<d)-1;//编号0到2^(d-1),至少为1
        int mid;
		while(l <= r) {
			mid = (l+r)/2;
			if(ok(root,mid,d)) l = mid+1;
			else r = mid-1;
		} 
		return (1<<d)-1+l;
    }
};
Published 152 original articles · won praise 2 · Views 6436

Guess you like

Origin blog.csdn.net/weixin_43918473/article/details/105460510