-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem81.cpp
More file actions
72 lines (62 loc) · 1.37 KB
/
problem81.cpp
File metadata and controls
72 lines (62 loc) · 1.37 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
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
string val;
TreeNode* left;
TreeNode* right;
TreeNode(string x) : val(x), left(NULL), right(NULL) {}
};
class DeepestRoots {
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 NULL;
TreeNode* root = new TreeNode(nodes[0]);
queue<TreeNode*> q;
q.push(root);
int i = 1;
while (!q.empty() && i < nodes.size()) {
TreeNode* curr = q.front(); q.pop();
if (nodes[i] != "null") {
curr->left = new TreeNode(nodes[i]);
q.push(curr->left);
}
i++;
if (i < nodes.size() && nodes[i] != "null") {
curr->right = new TreeNode(nodes[i]);
q.push(curr->right);
}
i++;
}
return root;
}
int maxDepth(TreeNode* node) {
if (!node) return 0;
int left = maxDepth(node->left);
int right = maxDepth(node->right);
return 1 + max(left, right);
}
void display() {
cout << maxDepth(root) << endl;
}
};
int main() {
DeepestRoots dr;
dr.readInput();
dr.display();
return 0;
}