Subtree of Another Tree
Check whether one tree appears inside another
DSA, Medium, Trees
Which structure or algorithm, and what does it cost.
You get two binary trees tree and sub. Your code may take the root nodes or the lists. Each node has val, left and right, null when missing. Either is fine; no conversion is needed. The examples use level-order lists. A list holds values row by row, left to right. Null marks a missing child. A missing node has no entries below it. An empty list is an empty tree. Return true if some node of tree, together with everything below it, has the same shape and values as sub. An empty sub always matches.
Examples
Constraints
- 0 <= number of nodes in
tree<= 30,000. - 0 <= number of nodes in
sub<= 30,000. - Each value is a whole number between -500 and 500.
- Values can repeat.
Your answer must contain
- The simple method and why it can be slow; the best method and why it is correct; code; time and memory cost; a hand trace of example 2.
Target Aim for O(n + m) time, where n and m are the two node counts.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
A match has to start at some node of the big tree. How would you test one starting node?
Hint 2 the approach
Testing every node can repeat a lot of work. Which nodes could never match, just from a single number that describes each subtree?
Hint 3 the key step
Compute the height of every node. Only a node whose height equals the height of sub can match, so run the full comparison only there.
Walkthrough
Full walkthrough brute force to best
Brute force
For every node of the big tree, compare the subtree below it with sub, node by node. One comparison can cost up to m steps and there are n nodes to start from, so this is O(n * m) time. With 30,000 nodes on each side and many equal values, that is far too slow.
Best method
A subtree that matches sub must have the same height as sub. Compute every height once, from the leaves upward. Then run the node-by-node comparison only at nodes whose height equals the height of sub. Two nodes with the same height cannot sit above one another, because a parent is always taller than its child. So their subtrees do not overlap, and all the comparisons together touch each node of the big tree at most once. The heights cost O(n + m), and the comparisons cost O(n) in total, so the work is linear.
Hand trace
Run on tree = [9, 4, 6, 2, 5, null, null, null, null, 1] and sub = [4, 2, 5]. In the big tree, 9 has children 4 and 6. Node 4 has children 2 and 5. Node 5 has a left child 1. The heights, from the leaves up, are 1: 1, 2: 1, 6: 1, 5: 2, 4: 3, 9: 4. The tree sub has a root 4 over two leaves, so its height is 2. Only node 5 has height 2, so only node 5 is compared with sub. Its value 5 differs from the sub root 4, so the result is false.
Code
def heights(top):
order = [top] if top else []
for node in order:
order.extend(child for child in (node.left, node.right) if child)
height = {}
for node in reversed(order):
height[node] = 1 + max(height.get(node.left, 0), height.get(node.right, 0))
return order, height
def same(x, y):
stack = [(x, y)]
while stack:
a, b = stack.pop()
if a is None and b is None:
continue
if a is None or b is None or a.val != b.val:
return False
stack.append((a.left, b.left))
stack.append((a.right, b.right))
return True
def is_subtree(root, target):
if target is None:
return True
order, height = heights(root)
need = heights(target)[1][target]
return any(height[node] == need and same(node, target) for node in order)Time and memory
O(n + m) time: the heights cost one pass over each tree, and the comparisons do not overlap. O(n + m) memory for the node lists and heights.
Common mistakes
- Matching only the top node and the first children. The whole subtree below the node must match, down to the leaves.
- Comparing only the value lists. The same values can be arranged as different trees.
- Treating an empty
subas not found. An empty tree matches anywhere, including an emptytree.