forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountCompleteTreeNodes.cpp
53 lines (47 loc) · 1.54 KB
/
CountCompleteTreeNodes.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
// Source : https://leetcode.com/problems/count-complete-tree-nodes/
// Author : Hao Chen
// Date : 2015-06-12
/**********************************************************************************
*
* Given a complete binary tree, count the number of nodes.
*
* Definition of a complete binary tree from Wikipedia:
* http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees
*
* In a complete binary tree every level, except possibly the last, is completely filled,
* and all nodes in the last level are as far left as possible.
* It can have between 1 and 2^h nodes inclusive at the last level h.
*
**********************************************************************************/
/**
* 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:
//return -1 if it is not.
int isCompleteTree(TreeNode* root) {
if (!root) return 0;
int cnt = 1;
TreeNode *left = root, *right = root;
for(; left && right; left=left->left, right=right->right) {
cnt *= 2;
}
if (left!=NULL || right!=NULL) {
return -1;
}
return cnt-1;
}
int countNodes(TreeNode* root) {
int cnt = isCompleteTree(root);
if (cnt != -1) return cnt;
int leftCnt = countNodes(root->left);
int rightCnt = countNodes(root->right);
return leftCnt + rightCnt + 1;
}
};