Height of Binary Tree After Subtree Removal Queries

Precompute per-node depth and best sibling height; for each query return the appropriate maximum.

Hard
Time O(n + q) Space O(n)
LeetCode
5 min read
tree dfs preprocessing

Problem#

Given the root of a binary tree with distinct values and a list of queries (each a node value), return the height of the tree (max depth in edges) after independently removing each queried subtree.

Examples#

  • root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4][2].
  • root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8][3,2,3,2].

Constraints#

  • 2 <= n <= 10^5, 1 <= queries.length <= 10^4.

Approach#

Two preprocessing DFSes. First, compute height[node] (depth of deepest descendant in edges) and depth[node] from root. Second, DFS preorder tracking bestWithout — the best answer if we removed the current node’s subtree — by combining the parent’s best with the sibling subtree’s “depth + height” contribution. Store per-node best.

Solution#

Height of Binary Tree After Subtree Removal Queries
class Solution {
public:
vector<int> treeQueries(TreeNode* root, vector<int>& queries) {
unordered_map<int,int> height, best;
function<int(TreeNode*)> getHeight = [&](TreeNode* u) -> int {
if (!u) return -1;
int h = 1 + max(getHeight(u->left), getHeight(u->right));
height[u->val] = h;
return h;
};
getHeight(root);
function<void(TreeNode*, int, int)> dfs = [&](TreeNode* u, int depth, int parentBest) {
if (!u) return;
best[u->val] = parentBest;
int lh = u->left ? height[u->left->val] : -1;
int rh = u->right ? height[u->right->val] : -1;
dfs(u->left, depth + 1, max(parentBest, depth + 1 + rh));
dfs(u->right, depth + 1, max(parentBest, depth + 1 + lh));
};
dfs(root, 0, 0);
vector<int> ans;
ans.reserve(queries.size());
for (int q : queries) ans.push_back(best[q]);
return ans;
}
};

Editorial#

When we remove a node’s subtree, the tree’s height is the best of: any path that doesn’t go through this node. The preorder pass threads parentBest (best ignoring the current subtree from upstream) plus the contribution from the sibling subtree (depth + 1 + siblingHeight). Each query is then O(1).

Complexity#

  • Time: O(n + q).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.