-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountCompleteTreeNodes.cpp
More file actions
36 lines (34 loc) · 920 Bytes
/
countCompleteTreeNodes.cpp
File metadata and controls
36 lines (34 loc) · 920 Bytes
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
// Source: https://leetcode.com/problems/count-complete-tree-nodes/
// Author: Miao Zhang
// Date: 2021-01-27
/**
* 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;
int left_height = getHeight(root->left);
int right_height = getHeight(root->right);
if (left_height == right_height) {
return pow(2, left_height) + countNodes(root->right);
} else {
return pow(2, right_height) + countNodes(root->left);
}
}
int getHeight(TreeNode* node) {
if (!node) return 0;
int height = 0;
while (node) {
height++;
node = node->left;
}
return height;
}
};