Same tree
Walk two trees simultaneously, checking structure and values at every node. About 9 minutes.
Comparing two trees at once
To check that two trees are identical, walk them together in lockstep, like two people following the same directions and comparing what they see at every turn.
At each step you look at one spot in each tree and ask two questions: do both have a node there, and do the nodes hold the same value?
Walk both trees in lockstep. Roots: both exist, both hold 1. So far so good.
The recursive step
If neither spot is empty and the two values match, then the trees are identical only if the left subtrees match each other and the right subtrees match each other. Both sides must be the same. A single mismatch anywhere means the answer is no.
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
left = is_same_tree(p.left, q.left)
right = is_same_tree(p.right, q.right)
return left and rightIf p is null and q is a node with val 1, what does is_same_tree return?
- Afalse
- Btrue
Show the answer
false. One tree has a node while the other is empty, so their shapes do not match.
Same tree
Given the roots of two binary trees p and q, return true if they are structurally identical and have the same node values. Otherwise, return false.
p = [1, 2, 3], q = [1, 2, 3] → true
0 ≤ number of nodes ≤ 10,000 · -1,000,000 ≤ node.val ≤ 1,000,000