forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
76 lines (55 loc) · 1.61 KB
/
main.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
74
75
76
/// Source : https://leetcode.com/problems/count-complete-tree-nodes/
/// Author : liuyubobobo
/// Time : 2018-08-02
#include <iostream>
#include <cassert>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/// Recursion
/// Time Complexity: O(h^2) where h is the height of the tree
/// Space Complexity: O(h)
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL)
return 0;
int leftLeft = leftHeight(root->left);
int leftRight = rightHeight(root->left);
if(leftLeft == leftRight)
return 1 + ((1<<leftLeft) - 1) + countNodes(root->right);
assert(leftLeft == leftRight + 1);
return 1 + ((1<<leftRight) - 1) + countNodes(root->left);
}
private:
int leftHeight(TreeNode* root){
if(root == NULL)
return 0;
return 1 + leftHeight(root->left);
}
int rightHeight(TreeNode* root){
if(root == NULL)
return 0;
return 1 + rightHeight(root->right);
}
};
int main() {
TreeNode* root = new TreeNode(1);
TreeNode* left = new TreeNode(2);
root->left = left;
TreeNode* right = new TreeNode(3);
root->right = right;
TreeNode* leftleft = new TreeNode(4);
root->left->left = leftleft;
TreeNode* leftright = new TreeNode(5);
root->left->right = leftright;
TreeNode* rightleft = new TreeNode(6);
root->right->left = rightleft;
cout << Solution().countNodes(root) << endl;
return 0;
}