-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path140. BurningTree.java
More file actions
43 lines (36 loc) · 896 Bytes
/
140. BurningTree.java
File metadata and controls
43 lines (36 loc) · 896 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
/*
class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
left = null;
right = null;
}
} */
class Solution {
public static int minTime(Node root, int target) {
int ans[]=new int[]{-1};
f(root,ans,target);
return ans[0];
}
public static int f(Node root,int ans[],int t){
if(root==null) return 0;
int left=f(root.left,ans,t);
int right=f(root.right,ans,t);
if(root.data==t){
ans[0]=Math.max(left,right);
return -1;
}
if(left<0){
ans[0]=Math.max(ans[0],Math.abs(left)+right);
return left-1;
}
if(right<0){
ans[0]=Math.max(ans[0],Math.abs(right)+left);
return right-1;
}
return 1+Math.max(right,left);
}
}