-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay41.cpp
More file actions
43 lines (40 loc) · 1.06 KB
/
Day41.cpp
File metadata and controls
43 lines (40 loc) · 1.06 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
/**
* Definition for a binary tree node.
* 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 ans = 0;
int solve(TreeNode* root, int start){
int d= 0;
if(root == NULL){
return d;
}
int ld = solve(root -> left, start);
int rd = solve(root -> right, start);
if(root -> val == start){
ans = max(ld, rd);
d = -1;
}
else if(ld >= 0 && rd >= 0){
d = max(ld, rd) + 1;
}
else{
int dis = abs(ld) + abs(rd);
ans = max(ans, dis);
d = min(ld, rd) - 1;
}
return d;
}
int amountOfTime(TreeNode* root, int start) {
solve(root, start);
return ans;
}
};