15% off all plans & roadmaps Use code

See plans

Height of Binary Tree After Subtree Removal Queries

Updated

TL;DR: Each query deletes one subtree, and you need the height of what remains. Compute, for every node, the deepest leaf you can reach without entering that node's subtree, and each query becomes one table lookup.

Problem

You are given the root of a binary tree with n nodes. Each node has a unique value from 1 to n. You are also given an array queries of size m.

You run m independent queries on the tree. In the ith query, you remove the subtree rooted at the node whose value is queries[i]. The value queries[i] is never equal to the root's value.

Return an array answer of size m, where answer[i] is the height of the tree after the ith query.

Note:

  • Each query is independent, so the tree returns to its initial state before the next query.
  • The height of a tree is the number of edges on the longest simple path from the root to any node.

Example 1

Input: root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4]
Output: [2]
Explanation: After removing the subtree rooted at 4, the height is 2. The longest path is 1 -> 3 -> 2.

Example 2

Input: root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8]
Output: [3,2,3,2]
Explanation:
- Removing the subtree at 3 leaves height 3 along 5 -> 8 -> 2 -> 4.
- Removing the subtree at 2 leaves height 2 along 5 -> 8 -> 1.
- Removing the subtree at 4 leaves height 3 along 5 -> 8 -> 2 -> 6.
- Removing the subtree at 8 leaves height 2 along 5 -> 9 -> 3.

Constraints

  • The number of nodes in the tree is n.
  • 2 <= n <= 10^5
  • 1 <= Node.val <= n
  • All values in the tree are unique.
  • m == queries.length
  • 1 <= m <= min(n, 10^4)
  • 1 <= queries[i] <= n
  • queries[i] != root.val

Constraints that matter

  • n up to 10^5 rules out recomputing the height for every query, which costs O(n * m) and reaches about 10^9 steps.
  • The tree can be a single chain of 10^5 nodes, so a recursive walk can exceed the stack in Python and some other runtimes.
  • m up to 10^4 means each query must cost close to O(1) after preprocessing, so the answers must be precomputed per node.
  • Values are unique and bounded by n, so a hash map or an array indexed by value can store one record per node.

View on LeetCode

Hints

Hint 1

Removing a subtree deletes only the paths that pass through the removed node.

Hint 2

The direct approach is to remove the subtree and walk the rest of the tree from the root.

Solution

Intuition

Removing a subtree deletes only the paths that pass through the removed node. Every other path survives. So the new height is the deepest leaf you can still reach without entering that subtree.

It is like a tree of water pipes fed from one main tank. Each junction gets a sticky note holding the longest pipe run that avoids its own branch, and a shutoff query reads that note.

For each node v, define best(v) as the deepest depth reachable outside v's subtree. A query then becomes one lookup: answer the value best(q). The hard part is computing best for every node in a single sweep. The outside depth of a node depends on its ancestors and on its siblings' subtrees.

The bottom-up half is a recursive postorder pattern. A node's height is 1 plus the larger child height, so children must be processed before their parent. The top-down half passes each child what its parent and its sibling contribute. Both halves are linear in the number of nodes.

Watch the pattern animation

Worked example

Input: root = [1,2,3], queries = [2,3]
Output: [1,1]
Explanation: Removing node 2 leaves the root with one child, 3, so the height is 1. Removing node 3 leaves the root with one child, 2, so the height is also 1. Each query is independent, so both answers use the original tree.

Approach 1: Brute force: rebuild the height for each query

The direct approach is to remove the subtree and walk the rest of the tree from the root. You track the depth of each node you visit and keep the largest depth. Each query repeats the whole walk, so the same nodes are visited again and again.

The walk skips any child whose value equals the query. Nothing else changes between queries, so the work per query is the size of the remaining tree.

Steps

  1. Set answer to an empty list.
  2. For each query value q, start a stack with the root at distance 0 and set best to 0.
  3. Pop a node and its distance. Update best with that distance.
  4. Push each child whose value is not q, with distance plus 1.
  5. When the stack is empty, append best to answer.

Dry run

Use root 1 with children 2 and 3, and queries [2, 3].

Query 2: the stack starts as [(1, 0)]. Pop (1, 0), so best = 0.

The left child 2 is skipped, and the right child 3 is pushed as (3, 1). Pop (3, 1), so best = 1.

The stack is empty, so the answer is 1.

Query 3: the stack starts as [(1, 0)]. Pop (1, 0), so best = 0.

The right child 3 is skipped, and the left child 2 is pushed as (2, 1). Pop (2, 1), so best = 1.

The answer is 1.

Final output: [1, 1].

Complexity

TimeO(n * m)
SpaceO(n)

Let n be the number of nodes and m the number of queries. Each query walks the remaining tree, which visits at most n nodes and does O(1) work on each. Repeating that for m queries gives O(n * m). The stack holds at most n entries, so the extra space is O(n) in the worst case.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:
        answer = []
        for q in queries:
            # Walk the tree again, skipping the removed subtree
            best = 0
            stack = [(root, 0)]
            while stack:
                node, d = stack.pop()
                best = max(best, d)
                if node.left and node.left.val != q:
                    stack.append((node.left, d + 1))
                if node.right and node.right.val != q:
                    stack.append((node.right, d + 1))
            answer.append(best)
        return answer

The Recursive Postorder Traversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Recursive Postorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: Precompute outside depth, then answer queriesOptimalRecursive Postorder Traversal

What is slow in the first approach is that every query revisits nodes whose answer never changes. The work for each query is the same walk over the same tree, so the total grows with m.

The insight that fixes it: the best depth outside a node's subtree depends only on three things. These are its parent's best value, the parent's own depth, and the deepest leaf in the sibling's subtree. You can compute that for every node in one top-down pass, then answer each query from the table.

Why it is correct. Any node outside v's subtree is reached through v's parent, so the parent's best value and the parent's own depth cover every outside path that goes above it. The only other outside paths go down into the sibling's subtree, and the deepest leaf there is the sibling's depth plus its height. Taking the max of these two never drops a candidate, so each stored value is exact.

Steps

  1. Visit the nodes in BFS order from the root, recording each node's depth. Parents appear before children.
  2. Walk the BFS order backward and compute each node's height in edges. A leaf has height 0, and an inner node has 1 plus the larger child height.
  3. Set best[root] to 0. Walk the BFS order forward.
  4. For each node, compute base = max(best[node], depth[node]).
  5. Set best[left] = max(base, depth[right] + height[right]) when the left child exists, and best[right] = max(base, depth[left] + height[left]) when the right child exists.
  6. Return best[q] for each query q.

Dry run

Use root 1 with children 2 and 3, and queries [2, 3].

Phase 1, BFS order: [1, 2, 3], with depth = {1: 0, 2: 1, 3: 1}.

Phase 2, heights from the back of the order: node 3 is a leaf, so height 0. Node 2 is a leaf, so height 0. Node 1 has children, so height = 1 + max(0, 0) = 1.

Phase 3, the top-down pass with the state after each step:

StepNode visitedbase = max(best[node], depth[node])Value set for childrenbest after step
11max(0, 0) = 0best[2] = max(0, depth[3] + height[3]) = max(0, 1) = 1; best[3] = max(0, depth[2] + height[2]) = max(0, 1) = 1{1: 0, 2: 1, 3: 1}
22max(1, 1) = 1none, node 2 is a leaf{1: 0, 2: 1, 3: 1}
33max(1, 1) = 1none, node 3 is a leaf{1: 0, 2: 1, 3: 1}

The queries read best[2] = 1 and best[3] = 1. The output is [1, 1].

Complexity

TimeO(n + m)
SpaceO(n)

Let n be the number of nodes and m the number of queries. The BFS visits each node once with O(1) map work, so that pass costs O(n). The height pass and the top-down pass each touch every node once and every child edge once, so each also costs O(n). Each query is one map lookup, which adds O(m) in total, and the maps and order list hold O(n) entries.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:
        # BFS order puts every parent before its children
        order = [root]
        depth = {root.val: 0}
        i = 0
        while i < len(order):
            node = order[i]
            i += 1
            for child in (node.left, node.right):
                if child:
                    depth[child.val] = depth[node.val] + 1
                    order.append(child)
        # Bottom-up: children are processed before their parent
        height = {}
        for node in reversed(order):
            h = 0
            for child in (node.left, node.right):
                if child:
                    h = max(h, height[child.val] + 1)
            height[node.val] = h
        # Top-down: best[v] is the deepest node outside the subtree of v
        best = {root.val: 0}
        for node in order:
            base = max(best[node.val], depth[node.val])
            left_cand = base
            right_cand = base
            if node.right:
                left_cand = max(left_cand, depth[node.right.val] + height[node.right.val])
            if node.left:
                right_cand = max(right_cand, depth[node.left.val] + height[node.left.val])
            if node.left:
                best[node.left.val] = left_cand
            if node.right:
                best[node.right.val] = right_cand
        return [best[q] for q in queries]

Common mistakes

  • Setting best for only one child, or copying the parent's value to both children. Each child needs its own sibling term, so set best[left] from the right sibling and best[right] from the left sibling.
  • Leaving depth[node] out of base. On the chain 1 -> 2 -> 3, removing 3 should give 1, but max(best[2], 0) without the depth term returns 0. The parent itself is a valid endpoint.
  • Returning height[root] for every query. That ignores the removal entirely, so the answer stays at the original height. The answer for node q is best[q].
  • Using a recursive DFS in Python on a chain of 10^5 nodes. The default recursion limit is about 1000, so the call raises RecursionError. Use the BFS order list, or an explicit stack.
  • Setting node.left = None for each query and forgetting to restore it. The queries must be independent, so the precomputed table stays read-only and each query only looks up a value.
  • Mixing node-count heights with edge depths. If leaves get height 1 while depth counts edges, every answer is off by one. Keep leaves at height 0 and count edges throughout.

Edge cases

  • Chain 1 -> 2 -> 3 -> 4 -> 5 with query 2: only the root remains, so the answer is 0.
  • Root 1 with left child 2 (a leaf) and right chain 3 -> 4 -> 5, with query 2: the remaining height is 3 along 1 -> 3 -> 4 -> 5.
  • Root 1 with left child 2 (with left child 4) and right leaf 3, with query 2: the remaining tree is 1 -> 3, so the answer is 1.
  • Two-node tree 1 -> 2 with query 2: the answer is 0, because only the root is left.
  • Maximum chain of 10^5 nodes with a query on the node at depth k: the answer is k - 1. The walk must be iterative to avoid stack overflow.
  • Several queries on the same node: each one returns the same value, because the table does not change between queries.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Height of Binary Tree After Subtree Removal Queries, with how to answer them.

Unlock the follow-ups

Height of Binary Tree After Subtree Removal Queries FAQ

What is the time complexity of Height of Binary Tree After Subtree Removal Queries?

The optimal approach runs in O(n + m) time, where n is the number of nodes and m is the number of queries. The brute force approach that rebuilds the height for each query costs O(n * m).

Why use a top-down pass for Height of Binary Tree After Subtree Removal Queries?

The answer for a node depends on what lies outside its subtree, which includes its ancestors and their other branches. A top-down pass hands each child the best value from its parent and sibling, so every node gets its answer in one sweep.

Can Height of Binary Tree After Subtree Removal Queries be solved in O(1) extra space?

No, not in the general case. Queries can ask about any node, so the answers for all nodes must be available, which takes O(n) space. The tree already uses O(n), so this is the honest bound.

Why does the Python solution avoid recursion?

A chain of 10^5 nodes creates a recursion depth of 10^5, which is far above Python's default limit. The BFS order list and reversed loop avoid recursion entirely and keep the same O(n + m) bound.

Asked at

See which companies ask this — Pro

Practise it