-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path222.cpp
More file actions
44 lines (37 loc) · 973 Bytes
/
Copy path222.cpp
File metadata and controls
44 lines (37 loc) · 973 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
37
38
39
40
41
42
43
44
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
if (root && root->left == nullptr) return 1;
int lh = lH(root);
int rh = rH(root);
if (lh == rh) return (1 << lh) - 1;
return 1 + countNodes(root->left) + countNodes(root->right);
}
int lH(TreeNode* node) {
int ht = 0;
while (node) {
ht++;
node = node->left;
}
return ht;
}
int rH(TreeNode* node) {
int ht = 0;
while (node) {
ht++;
node = node->right;
}
return ht;
}
};