-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0865.cpp
More file actions
46 lines (42 loc) · 1.36 KB
/
Copy path0865.cpp
File metadata and controls
46 lines (42 loc) · 1.36 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
class Solution {
public:
TreeNode *subtreeWithAllDeepest(TreeNode *root) {
int8_t height[1001] = {0};
stack<TreeNode *> s({root});
TreeNode *res;
int maxi = INT_MIN;
while (!s.empty()) {
TreeNode *root = s.top();
if (root->val >= 0) {
if (root->left) {
height[root->left->val] = height[root->val] + 1;
s.push(root->left);
}
if (root->right) {
height[root->right->val] = height[root->val] + 1;
s.push(root->right);
}
root->val = -root->val - 1;
continue;
}
s.pop();
root->val = -(root->val + 1);
if (!root->left && !root->right) {
if (height[root->val] > maxi) {
maxi = height[root->val];
res = root;
}
continue;
}
int8_t l = 0, r = 0;
if (root->left) l = height[root->left->val];
if (root->right) r = height[root->right->val];
if (l || r) height[root->val] = max(l, r);
if (height[root->val] >= maxi && l == r) {
maxi = height[root->val];
res = root;
}
}
return res;
}
};