leetcode #222 count complete binary tree element

LeetCode #222 Count Complete Binary Tree Element

Bruce Force / TLE

Simply use DFS and count, TLE.

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
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class {
public:
void DFS(TreeNode* root){
if (root == NULL){return;}
count ++;
DFS(root->left);
DFS(root->right);
}
int countNodes(TreeNode* root) {
DFS(root);
return count;
}
};

Divide and Conquer / AC

分别一直往左、一直往右找高度,若left_depth == right_depth,说明这一棵subtree是一棵complete tree,可以由公式计算出高度,若不相同,递归 return countNodes(root->left)+countNodes(root->right)+1;相当巧妙。
sigh,对分治的思想和完全树的性质理解地还不够到位。

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
class {
public:
int countLeft(TreeNode *root){
int left_height = -1;
while(root!=NULL){
left_height++;
root = root->left;
}
return left_height;
}
int countRight(TreeNode *root){
int right_height = -1;
while(root!=NULL){
right_height++;
root = root->right;
}
return right_height;
}
int countNodes(TreeNode* root) {
int left_depth = countLeft(root);
int right_depth = countRight(root);
if (left_depth == right_depth){
return ((1 << (left_depth+1)) - 1);
}
else{
return countNodes(root->left)+countNodes(root->right)+1;
}
}
};