Height of Binary Tree After Subtree Removal Queries - Problem
You are given the root of a binary tree with n nodes, where each node has a unique value from 1 to n. You must handle m independent queries, where each query asks: "What would be the height of the tree if I removed the subtree rooted at node X?"
For each query queries[i], you need to:
- Temporarily remove the entire subtree rooted at the node with value
queries[i] - Calculate the height of the remaining tree
- Restore the tree to its original state for the next query
Important: The height of a tree is the number of edges in the longest path from root to any leaf. An empty tree has height -1, and a single node has height 0.
Goal: Return an array where answer[i] is the height of the tree after removing the subtree in query i.
Input & Output
example_1.py โ Basic Tree
$
Input:
root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4]
โบ
Output:
[2]
๐ก Note:
The tree has height 3. When we remove the subtree rooted at node 4 (which includes nodes 4, 6, 5, 7), the remaining tree has nodes [1, 3, 2] with height 2 (path: 1โ3โ2).
example_2.py โ Multiple Queries
$
Input:
root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8]
โบ
Output:
[3,2,3,2]
๐ก Note:
Original tree height is 3. Removing node 3: height becomes 3. Removing node 2: height becomes 2. Removing node 4: height becomes 3. Removing node 8: height becomes 2.
example_3.py โ Edge Case
$
Input:
root = [1,null,5,3,null,2,4], queries = [3,5,4,2,1]
โบ
Output:
[1,0,1,1,-1]
๐ก Note:
When removing the root node 1, the tree becomes empty (height -1). Other removals leave various subtrees with different heights.
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
-
1 โค queries.length โค min(n, 104) -
1 โค queries[i] โค n -
queries[i] โ root.val
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Tree
First, measure the height of every branch and note the depth of each node from the root
2
Plan the Cuts
For each possible branch removal, calculate what the remaining tree height would be
3
Answer Queries
When asked about removing any specific branch, instantly provide the pre-calculated answer
Key Takeaway
๐ฏ Key Insight: Instead of recalculating the tree height for each query, we precompute the effect of removing every possible subtree. This transforms an O(nรm) problem into an O(n+m) solution by trading some space for massive time savings.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code