Approach
Depth-first search
For Height of Binary Tree After Subtree Removal Queries, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 37 lines of Java from the credited upstream file 2458.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] treeQueries(TreeNode root, int[] queries) {3 int[] ans = new int[queries.length];4 5 dfs(root, 0, 0);6 7 for (int i = 0; i < queries.length; ++i)8 ans[i] = valToMaxHeight.get(queries[i]);9 10 return ans;11 }12 13 14 private Map<Integer, Integer> valToMaxHeight = new HashMap<>();15 16 private Map<Integer, Integer> valToHeight = new HashMap<>();17 18 private int height(TreeNode root) {19 if (root == null)20 return 0;21 if (valToHeight.containsKey(root.val))22 return valToHeight.get(root.val);23 final int h = 1 + Math.max(height(root.left), height(root.right));24 valToHeight.put(root.val, h);25 return h;26 }27 28 29 private void dfs(TreeNode root, int depth, int maxHeight) {30 if (root == null)31 return;32 valToMaxHeight.put(root.val, maxHeight);33 dfs(root.left, depth + 1, Math.max(maxHeight, depth + height(root.right)));34 dfs(root.right, depth + 1, Math.max(maxHeight, depth + height(root.left)));35 }36}37