Same Tree
Check that two trees have the same shape and values
DSA, Easy, Trees
Which structure or algorithm, and what does it cost.
You get two binary trees a and b. 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. A list may end with extra nulls, so two different lists can describe one tree. Return true if both trees have the same shape and the same value at every position.
Examples
Constraints
- 0 <= number of nodes in each tree <= 30,000.
- Each list has at most 60,000 entries.
- Either tree can be empty.
Your answer must contain
- The simple method and its cost; the best method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n) time.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
If two trees are the same, what must be true of their two roots? What then follows for the children?
Hint 2 the approach
Each pair of places in the two trees gets the same question: both missing, one missing, or both present with equal values.
Hint 3 the key step
Keep a stack of node pairs, one from each tree, starting with the roots. On a mismatch the answer is false. Otherwise push the left pair and the right pair.
Walkthrough
Full walkthrough brute force to best
Brute force
Write each tree out as a list that records every missing child, for example in preorder with a mark for each gap, and compare the two lists. This is correct and O(n) time, but it builds two lists of O(n) size, and it cannot stop at the first difference.
Best method
Walk both trees at the same time, one pair of nodes at a time. A pair passes when both nodes are missing. A pair fails when only one is missing, or when both exist with different values. When a pair passes with two nodes, the trees are the same only if the left children also match and the right children also match. So keep a stack of pairs, starting with the two roots, and push the left pair and the right pair for every matching pair. Return false at the first failure. If the stack runs out, return true. Each pair is looked at once, so the work is linear, and the walk stops early on a difference.
Hand trace
Run on a = [6, 2, 9, null, 4] and b = [6, 2, 9, null, 4, null, null]. Stack [(6, 6)]. Pop (6, 6): equal, so push the left pair (2, 2) and then the right pair (9, 9). Pop (9, 9): equal, so push two pairs of missing children. Pop those two: both missing, they pass. Pop (2, 2): equal, so push the missing left pair and then (4, 4). Pop (4, 4): equal, so push two missing pairs. Pop the three missing pairs that remain. The stack is empty, so the answer is true.
Code
def is_same_tree(a, b):
stack = [(a, b)]
while stack:
x, y = stack.pop()
if x is None and y is None:
continue
if x is None or y is None or x.val != y.val:
return False
stack.append((x.left, y.left))
stack.append((x.right, y.right))
return TrueTime and memory
O(n) time, where n is the number of nodes in the larger tree, because each pair is popped once and there are at most two pairs per node. O(h) extra memory for the stack, where h is the height. A chain gives O(n).
Common mistakes
- Comparing only the values, for example the in-order lists. The trees [3, 5] and [3, null, 5] have the same values but a different shape.
- Comparing the two input lists directly. Extra nulls at the end of a list change the list but not the tree.
- Reading the fields of a missing node. Check for a missing node before you compare values.