Same Tree solution explained

Two binary trees are the same when they have the same shape and the same value at every position. Walk both trees together: if both nodes are missing, that spot matches; if only one is missing or the values differ, return false; otherwise compare the left children and the right children the same way. Each pair of nodes is checked once, so it runs in O(n) time.

By Published 6 min read

What counts as the same

You get the roots of two binary trees. Return true if they are identical: every node in one has a node in the same position in the other, with the same value, and neither tree has a node the other lacks. Two empty trees are the same. An empty tree and a non-empty tree are not.

  A:  1        B:  1          same values, different shape -> false
     /              \
    2                2

  C:   4       D:   4          identical -> true
      / \          / \
     2   6        2   6

  E:   4       F:   4          children swapped -> false
      / \          / \
     2   6        6   2
Pairs drawn for this page, with the result of the code below

Pair A and B is the one to remember. Both trees hold the values 1 and 2, and a plain preorder listing of values gives 1, 2 for each of them. Only the shape differs. Ask whether values can repeat and whether the trees could be very deep, since that affects whether recursion is safe.

Where it fits in an interview

Same Tree is a short warm-up, often the first tree question in a phone screen. It checks that you handle the empty-node cases cleanly, which is where most tree bugs live. It also sets up harder follow-ups: Subtree of Another Tree calls this exact function many times, and checking whether a tree is a mirror of itself is the same walk with the children crossed.

A straightforward first answer: flatten both

Turn each tree into a list by preorder traversal, writing a marker such as None every time a child is missing, then compare the lists. The markers make the encoding unique: two trees produce the same list exactly when they are identical. It takes O(n) time but builds two full lists before comparing anything, so it uses O(n) memory and cannot stop early.

def flatten(node, out):
    if node is None:
        out.append(None)  # mark the gap so shape is kept
        return out
    out.append(node.val)
    flatten(node.left, out)
    flatten(node.right, out)
    return out

def same_by_flattening(a, b):
    return flatten(a, []) == flatten(b, [])
Flatten with gap markers, then compare. O(n) time and O(n) memory. Nodes have val, left and right.

Lockstep walk

Instead of building lists, compare as you go. At each pair of positions there are only four situations. Both empty: they match, nothing more to check. Exactly one empty: shapes differ. Both present but values differ: not the same. Both present with equal values: the answer depends on both pairs of children. Writing the base case as "if either is missing, they match only if both are" covers the first two situations in one line.

def same_tree(a, b):
    if a is None or b is None:
        return a is b  # both empty is a match, one empty is not
    return (a.val == b.val
            and same_tree(a.left, b.left)
            and same_tree(a.right, b.right))
Python: recursive comparison with short-circuit and. O(n) time, O(h) stack.
function sameTree(a, b) {
  const pairs = [[a, b]];
  while (pairs.length > 0) {
    const [x, y] = pairs.pop();
    if (x === null && y === null) continue;
    if (x === null || y === null || x.val !== y.val) return false;
    pairs.push([x.left, y.left], [x.right, y.right]);
  }
  return true;
}
JavaScript: an explicit stack of node pairs, which avoids deep recursion.

The JavaScript version pushes pairs of nodes, not single nodes. That matters: the two trees must be visited in exactly the same order, and pairing them makes it impossible to drift. Using a queue instead of a stack also works and compares level by level.

Cost

n and m are the two tree sizes, h the height of the smaller tree
ApproachTimeExtra spaceStops early?
Flatten both with gap markersO(n + m)O(n + m)No
Recursive lockstep walkO(min(n, m))O(h) recursionYes
Iterative walk with a stack of pairsO(min(n, m))O(n) in the worst caseYes
n and m are the two tree sizes, h the height of the smaller tree. Scroll sideways on a small screen.

The walk never goes deeper than the smaller tree, because a missing node on one side ends that branch. That is why its cost depends on the smaller tree.

Edge cases

  • Both trees empty: true.
  • One empty, one a single node: false.
  • Same values in a different shape, as in pair A and B.
  • Children swapped, as in pair E and F.
  • Deep chains on both sides, where recursion depth could become a problem in Python.

Where it goes wrong

  • Comparing in-order value lists without gap markers. Many different trees share an in-order listing.
  • Checking a.val == b.val before checking for missing nodes, which crashes on a null.
  • Comparing node objects with == or is instead of their values. Two separately built trees normally share no nodes, so that test fails even for identical trees.
  • Returning true too early after matching only the left children.

Follow-ups

  • Is a tree symmetric? Compare the left subtree with the right subtree, pairing left.left with right.right and left.right with right.left.
  • Same up to swapping children at any node. At each pair, try both the straight and the crossed pairing of children.
  • Many trees, find the duplicates. Encode each subtree with gap markers and count the encodings in a hash map.
  • Compare in constant extra space. Use Morris traversal on both trees in step, which threads and unthreads temporary links.

A spoken answer

Fictional example

What a candidate might say
Candidate
I'll walk both trees together. If either node is missing, it's a match only when both are missing.
Candidate
If both are there, the values must match and so must the left pair and the right pair. The and short-circuits, so I stop at the first difference.
Candidate
That's linear in the smaller tree. If the trees could be very deep, I'd switch to a stack of node pairs to avoid recursion limits.

Next steps

Subtree of Another Tree reuses this comparison inside a search. Lowest Common Ancestor and Binary Tree Right Side View are the next tree problems in this group. Every walkthrough is listed on the coding problems hub.

How Natively can help you practice

A Mac or Windows desktop app, Natively can read a pair of tree drawings like these from a screenshot when you practice, then remind you which empty-node cases to cover first. Because it transcribes your mock round, you can go back and see whether you mentioned the shape-versus-values trap. See the coding interview assistant page for the coding features.

Questions people ask

How do you check if two binary trees are the same?

Compare them together, position by position. Two missing nodes match; one missing node or different values means false; otherwise both left children and both right children must match. It takes O(n) time.

Can I compare traversal lists to check if two trees are the same?

Only if you record missing children with a marker. Without markers, trees with different shapes can produce the same list of values, as with a node that has a left child versus a right child.

What is the space complexity of Same Tree?

O(h) for the recursion, where h is the height of the smaller tree. That is O(log n) for a balanced tree and O(n) for a chain.

How is Same Tree related to Symmetric Tree?

Symmetric Tree runs the same lockstep walk on the root's two subtrees, but crosses the children: left with right and right with left.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP