Height of Binary Tree After Subtree Removal Queries - Problem
You are given the root of a binary tree with n nodes. Each node is assigned a unique value from 1 to n. You are also given an array queries of size m.
You have to perform m independent queries on the tree where in the ith query you do the following:
- Remove the subtree rooted at the node with the value
queries[i]from the tree. It is guaranteed thatqueries[i]will not be equal to the value of the root.
Return an array answer of size m where answer[i] is the height of the tree after performing the ith query.
Note:
- The queries are independent, so the tree returns to its initial state after each query.
- The height of a tree is the number of edges in the longest simple path from the root to some node in the tree.
Input & Output
Example 1 — Basic Tree
$
Input:
root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [3,6,4,5]
›
Output:
[3,3,2,2]
💡 Note:
After removing node 3: height becomes 3 (path 1→4→5→7). After removing node 6: height becomes 3 (path 1→4→5→7). After removing node 4: height becomes 2 (path 1→3→2). After removing node 5: height becomes 2 (path 1→3→2).
Example 2 — Smaller Tree
$
Input:
root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8]
›
Output:
[3,2,3,2]
💡 Note:
After removing different subtrees, the remaining tree has various maximum heights depending on which nodes remain and their depths.
Constraints
-
The number of nodes in the tree is
n. -
2 ≤ n ≤ 105 -
1 ≤ Node.val ≤ n - All the values in the tree are unique.
-
m == queries.length -
1 ≤ m ≤ min(n, 104) -
1 ≤ queries[i] ≤ n -
queries[i] ≠ root.val
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with unique node values 1 to n
2
Remove Subtree
Remove the subtree rooted at the queried node
3
Calculate Height
Find the height of the remaining tree structure
Key Takeaway
🎯 Key Insight: Precompute alternative heights using DFS to answer queries in O(1) time instead of recalculating each time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code