Tree Height After Removing Each Queried Subtree Independently

Last updated: November 29, 2026

Quick Overview

Given a binary tree with unique values and many queries, each query names a non-root node. For each query independently, return the height of the tree (in edges) if that node's entire subtree were removed.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given a binary tree with unique values and many queries, each query names a non-root node. For each query independently, return the height of the tree (in edges) if that node's entire subtree were removed.

A Google onsite hard question in the style of what-if analysis on a dependency tree. Recomputing per query is O(n * q); the interviewer looks for precomputing, for each node, the best height achievable from everything outside its subtree.

What the Interviewer Expects
  • Reject O(n) per query recomputation
  • Precompute depth and subtree height for every node
  • Pass down the best height available outside the current subtree
  • Combine sibling heights correctly when moving to a child
  • Answer each query in O(1)
Key Topics to Cover
binary trees
rerooting
precomputation
tree dynamic programming
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if removals accumulate instead of being independent?
  • Answer the same question for diameter instead of height.
  • Generalize to n-ary trees where a node has many siblings.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: root with n unique values and a list of q query values, none of them the root. Output: list of heights in edges, one per query, each computed on the original tree minus that query's subtree....

High-Level Design

Let depth(x) be the edge distance from the root and h(x) the height of x's subtree in edges (leaf is 0, None is -1). Removing x leaves every node outside x's subtree. Define out(x) as the maximu...


Submit Your Answer
Markdown supported