Problem Description
Given a binary tree with unique node values and an array of queries, for each query you must remove the entire subtree rooted at the given node (note that the root is never removed). The query is independent – meaning after each removal the tree is restored to its initial state. Return an array where each entry is the height of the tree (defined as the number of edges on the longest path from the root to any node) after performing the subtree removal.
Key Insights
- The removal of a subtree can only affect paths that go through the removed branch.
- We can leverage a two-pass tree dynamic programming technique:
- The first DFS (bottom-up) computes the height (subtree-depth) of each node.
- The second DFS (top-down) propagates the best “alternative” height from ancestors (the value of the tree outside the current subtree).
- For any query removal at node q, the new height of the tree becomes the maximum height that can be achieved without using any node in the subtree rooted at q. This is captured by the propagated value “up[q]” computed during the second DFS.
Space and Time Complexity
Time Complexity: O(n) for the two DFS traversals (n is the number of nodes).
Space Complexity: O(n) due to recursion stack and auxiliary arrays to store depths and parent-side values.
Solution
We solve the problem in two main steps:
- Use a DFS (Depth-First Search) from the root to compute for each node the height of its subtree (i.e. the maximum distance from the node to a leaf in its subtree). This “subtree height” is stored for each node.
- Use a second DFS to compute an “up” value for every node. The up value represents the maximum distance from the root to a node that does not lie in the current node’s subtree. For a child, this can be computed from its parent’s up value (increased by one) or, if the sibling branch offers a longer route, using that information.
With these two pieces of data, the answer for each query (removing the subtree rooted at node q) is simply up[q] because the maximum height of the tree post-removal will be determined by the best path from above q that avoids q's subtree.