-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode_2458.java
53 lines (40 loc) · 1.83 KB
/
Leetcode_2458.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
52
53
class Solution {
// Array to store the maximum height of the tree after removing each node
static final int[] maxHeightAfterRemoval = new int[100001];
int currentMaxHeight = 0;
public int[] treeQueries(TreeNode root, int[] queries) {
traverseLeftToRight(root, 0);
currentMaxHeight = 0; // Reset for the second traversal
traverseRightToLeft(root, 0);
// Process queries and build the result array
int queryCount = queries.length;
int[] queryResults = new int[queryCount];
for (int i = 0; i < queryCount; i++) {
queryResults[i] = maxHeightAfterRemoval[queries[i]];
}
return queryResults;
}
private void traverseLeftToRight(TreeNode node, int currentHeight) {
if (node == null) return;
// Store the maximum height if this node were removed
maxHeightAfterRemoval[node.val] = currentMaxHeight;
// Update the current maximum height
currentMaxHeight = Math.max(currentMaxHeight, currentHeight);
// Traverse left subtree first, then right
traverseLeftToRight(node.left, currentHeight + 1);
traverseLeftToRight(node.right, currentHeight + 1);
}
private void traverseRightToLeft(TreeNode node, int currentHeight) {
if (node == null) return;
// Update the maximum height if this node were removed
maxHeightAfterRemoval[node.val] = Math.max(
maxHeightAfterRemoval[node.val],
currentMaxHeight
);
// Update the current maximum height
currentMaxHeight = Math.max(currentHeight, currentMaxHeight);
// Traverse right subtree first, then left
traverseRightToLeft(node.right, currentHeight + 1);
traverseRightToLeft(node.left, currentHeight + 1);
}
}