Height of Binary Tree After Subtree Removal Queries — LeetCode 2458 Python Solution

HardTreeDepth-First SearchBreadth-First SearchArrayBinary Tree
Problem
#2458
Reading time
5 min

The problem

You are given the root of a binary tree with n nodes. Each node is assigned a unique value from 1 to n.

Example

Input
root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4]
Output
[2]
Explanation
The diagram above shows the tree after removing the subtree rooted at node with value 4.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:
        def f(root):
            if root is None:
                return 0
            l, r = f(root.left), f(root.right)
            d[root] = 1 + max(l, r)
            return d[root]

        def dfs(root, depth, rest):
            if root is None:
                return
            depth += 1
            res[root.val] = rest
            dfs(root.left, depth, max(rest, depth + d[root.right]))
            dfs(root.right, depth, max(rest, depth + d[root.left]))

        d = defaultdict(int)
        f(root)
        res = [0] * (len(d) + 1)
        dfs(root, -1, 0)
        return [res[v] for v in queries]

Complexity

MeasureComplexity
TimeO(n+m)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2458. Height of Binary Tree After Subtree Removal Queries is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2458. Height of Binary Tree After Subtree Removal Queries?
LeetCode 2458. Height of Binary Tree After Subtree Removal Queries is rated Hard on LeetCode.
What is the time complexity of LeetCode 2458. Height of Binary Tree After Subtree Removal Queries?
The Python solution on this page runs in O(n+m).
What is the space complexity of LeetCode 2458. Height of Binary Tree After Subtree Removal Queries?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2458. Height of Binary Tree After Subtree Removal Queries cover?
LeetCode 2458. Height of Binary Tree After Subtree Removal Queries is tagged Tree, Depth-First Search, Breadth-First Search, Array and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview