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 that queries[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
Height of Binary Tree After Subtree RemovalOriginal Tree1342657Height: 4→ Remove Node 3 →After Removal14657Height: 3Query Result: Height becomes 3 after removing subtree rooted at node 3
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
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
15.0K Views
Medium Frequency
~35 min Avg. Time
340 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen