-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountCompleteTreeNodes.cc
66 lines (49 loc) · 1.19 KB
/
CountCompleteTreeNodes.cc
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
55
56
57
58
59
60
61
62
63
64
#include "leet.h"
#include <algorithm>
#include <cstring>
class Solution{
public:
int height;
int countNodes(TreeNode *root) {
if (!root) {
return 0;
}
height = 0;
for (auto now = root; now; now = now->left) ++height;
int mark = 1;
int ans = 1;
auto now = root;
const int hint = 1 << (height - 1);
for (;;) {
if (mark >= hint) {
ans = mark;
}
if (!now || !now->left) break;
auto mk = mark << 1;
auto n = now->left;
while (n->right) {
n = n->right;
mk = mk << 1 | 1;
}
if (mk < hint) {
now = now->left;
mark <<= 1;
} else {
ans = mk;
if (now->right) {
now = now->right;
mark = mark << 1 | 1;
} else {
break;
}
}
}
return ans;
}
};
int main(){
Solution slu;
auto root = Serialize::treenode({1,2,3});
cout << slu.countNodes(root) << endl;
return 0;
}