-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path222.cpp
73 lines (72 loc) · 1.61 KB
/
222.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// recursion.cpp
/**
* 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)
return 0;
TreeNode *l = root, *r = root;
int ld = 0, rd = 0;
while (l) {
++ld;
l = l->left;
}
while (r) {
++rd;
r = r->right;
}
if (ld == rd)
return (1 << ld) - 1;
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
// somethingFaster.cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution2 {
public:
int countNodes(TreeNode *root) {
int Deep = 0, result = 0;
if (!root)
return 0;
TreeNode *temp = root, *cur = root;
while (temp) {
Deep++;
temp = temp->left;
}
int parentHigh = Deep; //父节点的高度,也就是当前节点的高度
while (
parentHigh >
1) { // parentHigh表示当前节点,因为要计算子节点即curHigh,所以不能等于0
cur = root->left;
int curHigh = parentHigh - 1; //当前节点的子节点高度
for (int i = curHigh; i > 1; i--)
cur = cur->right;
if (cur) {
root = root->right;
result += 1 << (curHigh - 1);
} else {
root = root->left;
}
parentHigh--;
}
if (root)
result++;
return result + (1 << (Deep - 1)) - 1;
}
};