Skip to content

Commit 7d207fa

Browse files
committed
count_complete_tree_nodes
1 parent cc1d44e commit 7d207fa

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,9 +175,10 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
175175
#### [215. Kth Largest Element in an Array](https://github.com/hitzzc/go-leetcode/tree/master/kth_largest_element_in_an_array)
176176
#### [216. Combination Sum III](https://github.com/hitzzc/go-leetcode/tree/master/combinations_sum_III)
177177
#### [217. Contains Duplicate](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate)
178-
#### [218. Contains Duplicate II](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_II)
179-
#### [219. Contains Duplicate III (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_III)
178+
#### [219. Contains Duplicate II](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_II)
179+
#### [220. Contains Duplicate III (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_III)
180180
#### [221. Maximal Square](https://github.com/hitzzc/go-leetcode/tree/master/maximal_square)
181+
#### [222. Count Complete Tree Nodes](https://github.com/hitzzc/go-leetcode/tree/master/count_complete_tree_nodes)
181182

182183

183184

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
struct TreeNode {
2+
int val;
3+
TreeNode *left;
4+
TreeNode *right;
5+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
6+
};
7+
8+
class Solution {
9+
public:
10+
int countNodes(TreeNode* root) {
11+
int depth = 0;
12+
TreeNode *left, *right;
13+
left = right = root;
14+
while (left!=NULL && right!=NULL){
15+
left = left->left;
16+
right = right->right;
17+
++depth;
18+
}
19+
if (left==NULL && right==NULL)
20+
return (1<<depth) - 1;
21+
int cnt1 = countNodes(root->left);
22+
int cnt2 = countNodes(root->right);
23+
return cnt1 + cnt2 + 1;
24+
}
25+
};

0 commit comments

Comments
 (0)