-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem83.cpp
More file actions
89 lines (73 loc) · 1.68 KB
/
problem83.cpp
File metadata and controls
89 lines (73 loc) · 1.68 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class CompleteTreeCounter {
string line;
TreeNode *root;
public:
void readInput() {
getline(cin, line);
if (line.empty()) {
cout << "!! Invalid Input !!" << endl;
exit(1);
}
root = buildTree();
}
TreeNode *buildTree() {
istringstream iss(line);
string val;
vector<string> nodes;
while (iss >> val) nodes.push_back(val);
if (nodes[0] == "null") return nullptr;
TreeNode *root = new TreeNode(stoi(nodes[0]));
queue<TreeNode*> q;
q.push(root);
int i = 1;
while (!q.empty() && i < nodes.size()) {
TreeNode *curr = q.front();
q.pop();
if (i < nodes.size() && nodes[i] != "null") {
curr->left = new TreeNode(stoi(nodes[i]));
q.push(curr->left);
}
i++;
if (i < nodes.size() && nodes[i] != "null") {
curr->right = new TreeNode(stoi(nodes[i]));
q.push(curr->right);
}
i++;
}
return root;
}
int countNodes(TreeNode *node) {
if (!node) return 0;
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
if (leftDepth == rightDepth) {
return (1 << leftDepth) + countNodes(node->right);
} else {
return (1 << rightDepth) + countNodes(node->left);
}
}
int getDepth(TreeNode *node) {
int d = 0;
while (node) {
d++;
node = node->left;
}
return d;
}
void display() {
cout << countNodes(root) << endl;
}
};
int main() {
CompleteTreeCounter ctc;
ctc.readInput();
ctc.display();
return 0;
}