Height After Subtree Removal Queries

Given a rooted tree and several queries, each query removes the subtree rooted at a given node. Return the height of the remaining tree for every query. This is a rerooting problem because the answer for one node can be derived from information computed for its ancestors and siblings.

Input Format

n, edges, queries describe a rooted tree and subtree removals

Output Format

tree height after removing each queried subtree

Constraints

  • 1 <= n <= 10^5
  • edges.length = n-1
  • queries.length <= 10^5
  • The tree is rooted at 1 in the standard formulation.

Examples

Example 1:

Input:

n = 5
edges = [[1,2],[1,3],[3,4],[3,5]]
queries = [3,4,5]

Output:

[1,2,2]

Explanation:

Removing node 3 leaves only path 1-2 with height 1. Removing leaf subtrees 4 or 5 keeps height 2.

Example 2:

Input:

n = 4
edges = [[1,2],[2,3],[2,4]]
queries = [2,3]

Output:

[0,2]

Explanation:

Removing the subtree of node 2 leaves only the root. Removing node 3 keeps the longest remaining path length at 2.

Loading...
Height After Subtree Removal Queries