forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path222.Count-Complete-Tree-Nodes_v2.cpp
54 lines (52 loc) · 1.15 KB
/
222.Count-Complete-Tree-Nodes_v2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* 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)
{
int h = 0;
TreeNode* node = root;
while (node!=NULL)
{
h++;
node = node->left;
}
int low = (1<<(h-1));
int hi = (1<<h)-1;
while (low<hi)
{
int mid = low+(hi-low+1)/2;
if (hasK(root,mid))
low = mid;
else
hi = mid-1;
}
return low;
}
bool hasK(TreeNode* root, int K)
{
vector<int>path;
while (K>0)
{
path.push_back(K);
K = K/2;
}
for (int i=path.size()-1; i>=0; i--)
{
if (root==NULL) return false;
if (i==0) return true;
if (path[i-1]==path[i]*2)
root = root->left;
else
root = root->right;
}
return true;
}
};