Same Tree, visualized step by step

Easy One of the Blind 75 interview problems (LeetCode 100). Technique: tree recursion. Solution in Python, explained at every step.

The problem

You get the roots of two binary trees, p and q. They are the same when they have the same shape and the same value in every node: each node of one tree has a node with the same value in the same place in the other. Return whether they are the same.

Example: two trees, each with 5 at the root, 3 and 8 under it, and 1 and 4 under 3, are the same. If the second tree has no 4 under its 3, they are not.

Two trees side by side, each with 5 at the root, 3 on the left and 8 on the right, and 1 and 4 under 3. Answer: yes. The same first tree beside a second one whose 3 has only the left child 1; where the 4 would be, an empty mark. Answer: no.
Same values are not enough: one missing node makes the answer no.

Try it yourself first: LeetCode 100 ↗. Then step through the solution below.

Brute force

Write each tree out as a list, in preorder, with a mark for every empty child, and compare the two lists. That is linear time, O(n + m) for trees of n and m nodes, but it builds both lists in full and reads both trees to the end, even when their roots already differ. Leave out the marks, and two different shapes can give the same list.

The key insight

The clue is in the words "the same value in the same place". Two trees are the same when their roots hold the same value, their left subtrees are the same, and their right subtrees are the same. Each subtree pair is the same problem on smaller trees.

So a call compares one pair of nodes. Two empty nodes are the same; one empty node against a node is not; two nodes with different values are not. Otherwise the answer is the two calls on the children, joined by and: a no from the left children ends it without comparing the right ones.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Same Tree, step by step

Python

class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, right def is_same_tree(p, q):    if p is None and q is None:        return True    if p is None or q is None:        return False    if p.val != q.val:        return False    return (is_same_tree(p.left, q.left)            and is_same_tree(p.right, q.right))
All steps as text
  1. Two trees, p and q. They are the same if they have one shape with the same value in each place. Are they?
  2. The function is called on the roots, 5 and 5: both are nodes and both hold 5, so the answer depends on their children.
  3. The call on 5 and 5 compares their left children first: it calls the function on 3 and 3.
  4. Now p and q are the two 3s, and the call on 5 and 5 waits. Both are nodes and both hold 3: on to their children.
  5. The call on 3 and 3 calls the function on their left children, 1 and 1.
  6. Now p and q are the two 1s, leaves: both are nodes and both hold 1, so on to their children.
  7. The call on 1 and 1 calls the function on their left children: both are empty (∅).
  8. Now p and q are the left children of 1 and 1, both empty (∅): two empty trees are the same, so this call returns yes.
  9. The left children matched, so the call on 1 and 1 now compares the right ones, both empty (∅).
  10. Now p and q are the right children of 1 and 1, also empty (∅): this call returns yes too.
  11. Both pairs of children matched, so the call on 1 and 1 returns yes.
  12. The left children matched, so the call on 3 and 3 now compares the right ones, 4 and 4.
  13. Now p and q are the two 4s, leaves: both are nodes and both hold 4, so on to their children.
  14. The call on 4 and 4 calls the function on their left children: both are empty (∅).
  15. Now p and q are the left children of 4 and 4, both empty (∅): two empty trees are the same, so this call returns yes.
  16. The left children matched, so the call on 4 and 4 now compares the right ones, both empty (∅).
  17. Now p and q are the right children of 4 and 4, also empty (∅): this call returns yes too.
  18. Both pairs of children matched, so the call on 4 and 4 returns yes.
  19. Both pairs of children matched, so the call on 3 and 3 returns yes.
  20. The left children matched, so the call on 5 and 5 now compares the right ones, 8 and 8.
  21. Now p and q are the two 8s, leaves: both are nodes and both hold 8, so on to their children.
  22. The call on 8 and 8 calls the function on their left children: both are empty (∅).
  23. Now p and q are the left children of 8 and 8, both empty (∅): two empty trees are the same, so this call returns yes.
  24. The left children matched, so the call on 8 and 8 now compares the right ones, both empty (∅).
  25. Now p and q are the right children of 8 and 8, also empty (∅): this call returns yes too.
  26. Both pairs of children matched, so the call on 8 and 8 returns yes.
  27. Both subtrees matched, so the first call returns yes: the trees are the same.
  28. Every pair of nodes was compared once: O(n) time, with as many calls waiting as the trees are deep: O(h) space.
Same Tree, step by step. Last step: Every pair of nodes was compared once: O(n) time, with as many calls waiting as the trees are deep: O(h) space.

Note

In Java and C++ the return is written with &&, which stops at the first false just as Python's and does: when the left children differ, the right ones are never compared.

Complexity

ApproachTimeSpace
Brute force: write both trees out with empty marks, compareO(n + m)O(n + m)
A queue of node pairs instead of recursionO(n)O(w)
Compare the roots, then both pairs of children, recursively this pageO(n)O(h)

n and m are the numbers of nodes in the two trees, n the smaller; h and w are the smaller tree's height and the number of nodes on its widest level.

  • Time: O(n). Each pair of nodes is compared once, n for the smaller tree; a difference stops the comparison early.
  • Space: O(h). The calls wait on the call stack, one per level: O(log n) for balanced trees, O(n) for trees that are one long chain.

Note

One call compares one pair, so the calls nest as deep as the two trees share a path. Python allows 1,000 nested calls by default: two chains of about a thousand nodes raise RecursionError, even when they are equal. In Java and C++ no number is set: the thread's stack size decides. The queue of pairs in the follow-up has no such limit.

Edge cases

  • Two empty trees: the first check answers yes: two empty trees are the same.
  • One empty tree: the second check answers no at once.
  • The same values in another shape, like 1 with a left child 2 against 1 with a right child 2: the roots match, then the left children are 2 and an empty child, so the answer is no.
  • The same shape, one value different, like 1 over 2 and 3 against 1 over 2 and 4: the 3 and the 4 meet in the last call, which returns no.

When the answer is no

The same code on trees that differ in one place: 3 has a right child, 4, in the first tree and none in the second. Up to step 11 it runs as before; at step 12 the trees part. Press → for each step.

Same Tree, when the answer is no

Python

class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, right def is_same_tree(p, q):    if p is None and q is None:        return True    if p is None or q is None:        return False    if p.val != q.val:        return False    return (is_same_tree(p.left, q.left)            and is_same_tree(p.right, q.right))
All steps as text
  1. The second tree has no right child under its 3. Are the two trees the same now?
  2. The function is called on the roots, 5 and 5: both are nodes and both hold 5, so the answer depends on their children.
  3. The call on 5 and 5 compares their left children first: it calls the function on 3 and 3.
  4. Now p and q are the two 3s, and the call on 5 and 5 waits. Both are nodes and both hold 3: on to their children.
  5. The call on 3 and 3 calls the function on their left children, 1 and 1.
  6. Now p and q are the two 1s, leaves: both are nodes and both hold 1, so on to their children.
  7. The call on 1 and 1 calls the function on their left children: both are empty (∅).
  8. Now p and q are the left children of 1 and 1, both empty (∅): two empty trees are the same, so this call returns yes.
  9. The left children matched, so the call on 1 and 1 now compares the right ones, both empty (∅).
  10. Now p and q are the right children of 1 and 1, also empty (∅): this call returns yes too.
  11. Both pairs of children matched, so the call on 1 and 1 returns yes.
  12. The left children matched, so the call on 3 and 3 now compares the right ones, 4 and an empty child (∅).
  13. Now p is 4 and q is empty (∅): one tree has a node where the other has none. This call returns no.
  14. The right children differ, so the call on 3 and 3 returns no.
  15. The left subtrees differ, so the right children, 8 and 8, are never compared: the first call returns no.
  16. A no from one pair is the answer for the whole trees, so a difference stops the work early. O(n) is the worst case.
Same Tree, when the answer is no. Last step: A no from one pair is the answer for the whole trees, so a difference stops the work early. O(n) is the worst case.

Try it: put Same Tree together step by step

The blocks below are steps of Same Tree in words, and two of them do not belong. A block that compares two children “the same way” runs your lines again, from line 1, on that pair of children. Put the right ones in order and check: your algorithm runs on the example and on the two trees of the walkthrough "When the answer is no", so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Same Tree together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong.

Your algorithm

To compare the trees under p and q:

Blocks

Interview follow-up

Can you compare the two trees without recursion? Yes, with a queue of pairs: put in the two roots, and each time take a pair out. Two empty nodes match, so go on to the next pair; one empty node, or two different values, answer no at once; otherwise put in the pair of left children and the pair of right children. When the queue runs empty, the answer is yes. The same O(n) time, and a very deep tree cannot hit the recursion limit.

What if the second tree may sit anywhere inside the first? That is Subtree of Another Tree (LeetCode 572): run this comparison from every node of the big tree, O(m · n) for trees of m and n nodes. Writing both trees out with empty marks and a separator before every value, so that 2 is not found inside 12, and searching one string in the other with a linear-time search, such as KMP, brings it down to O(m + n).

The data structure behind it

  • Preorder traversal: the order these calls visit the pairs: the roots, then the left subtrees, then the right ones.
  • Binary search tree: its shape depends on the order the values go in: 5, 3, 8 and 3, 5, 8 build two trees that this comparison tells apart.