-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
51 lines (48 loc) · 1.31 KB
/
Solution.java
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private Map<TreeNode, Integer> d = new HashMap<>();
private int[] res;
public int[] treeQueries(TreeNode root, int[] queries) {
f(root);
res = new int[d.size() + 1];
d.put(null, 0);
dfs(root, -1, 0);
int m = queries.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
ans[i] = res[queries[i]];
}
return ans;
}
private void dfs(TreeNode root, int depth, int rest) {
if (root == null) {
return;
}
++depth;
res[root.val] = rest;
dfs(root.left, depth, Math.max(rest, depth + d.get(root.right)));
dfs(root.right, depth, Math.max(rest, depth + d.get(root.left)));
}
private int f(TreeNode root) {
if (root == null) {
return 0;
}
int l = f(root.left), r = f(root.right);
d.put(root, 1 + Math.max(l, r));
return d.get(root);
}
}