progress

~/problems / Trees / Binary trees

Same Tree

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min

Two backups of the same tree should be identical.

TreeNode(val, left=None, right=None) is in the starter. Keep it.

Write trees_match(a, b) -> bool: True when the trees rooted at a and b have the same shape and the same values in the same places. Two empty trees (None) match.

#     a:  4        b:  4        c:  4
#        / \          / \          / \
#       2   7        2   7        7   2
trees_match(a, b)         # True
trees_match(a, c)         # False: the children are swapped

#     d:  1        e:  1
#        /              \
#       3                3
trees_match(d, e)         # False: same values, different shape
trees_match(None, None)   # True

Up to 5,000 nodes per tree; values may repeat. Aim for O(n) and stop at the first difference.

Show hint

Two trees match when their roots match and both pairs of subtrees match. Decide what happens when one or both sides are empty.

Topic: Binary trees. Recursive return values (height, best path), BFS by level, BST invariants.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc