Same Tree
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Decide whether two binary trees have the same shape and the same values.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1What if both nodes are empty? What if only one is?
- Hint 2Same values here AND same left subtrees AND same right subtrees.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Two people compare two family trees. At each position they check: both empty? fine. Only one empty? different. Both people present but with different names? different. If the names match, they compare the left children together and then the right children together.
- The obvious way
No cheaper way: every node of both trees has to be compared once.
- The key insight
Two trees are the same when: both are empty, or both nodes exist with equal values and their left subtrees are the same and their right subtrees are the same. Anything else is different.
- The algorithm
- Both empty? Same.
- Only one empty, or values differ? Different.
- Otherwise the answer is: left subtrees same AND right subtrees same.
Watch it run
Examplefirst = [1, 2, 3], second = [1, 2, 3]
Roots: 1 and 1 are equal. Now compare the left children.
roots equal
Where people slip
- Handle the "both empty" case first so you never read .val of nothing.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def is_same_tree(p, q):
if p is None and q is None:
return True # both empty: same
if p is None or q is None or p.val != q.val:
return False # only one empty, or different values
return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)Now close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.