Skip to content
mlmentorship

Compare aligned values and missing-child positions together

Match values and corresponding child positions, then change alignment or ignore labels explicitly.

Published · 10 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Compare aligned values and missing-child positions together

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. Two roots, first and second, of finite binary trees without cycles or shared children. Output. Return True exactly when all corresponding node values and child positions match. Rules. Compare structure as well as values; a left child does not match a right child. Values use Python ==. Nodes need not have the same object identities. Preserve both trees. Two empty trees match; exactly one empty tree does not. Example. Root 1 with children 2 and 3 does not match root 1 with only left child 2. Their compact level-order notations are [1, 2, 3] and [1, 2, null]; return False.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Two trees match only if the same-position node pair passes the null, value, left-pair, and right-pair checks.

Problem trace

Matching values are insufficient when corresponding child structure differs

Input and goalCheck whether two binary trees have the same shape and values.
Pair the two rootsCompare A = [1,2,3] with B = [1,2,null]. Both roots exist and 1 == 1, so Python continues across the and-chain to the left pair.

Tree A

Tree B

callStack[(A:1,B:1)]checkboth real; 1 == 1
node A:1 = B:1
compare pair
call stack
[(A:1,B:1)]
check
both real; 1 == 1

Recognize it
Use paired DFS when equality, symmetry, or structural correspondence requires comparing both value and shape at the same tree positions rather than comparing traversed value sequences.
Keep true
same_tree(first, second) returns true exactly when the two subtrees rooted at that pair have identical shape and equal values at every corresponding node.
Reuse it
When comparing recursive structures, recurse on aligned pairs and make missing-object cases explicit before reading values; this transfers to mirror symmetry, subtree equality, and AST comparison.
Compare A = [1,2,3] with B = [1,2,null]. Both roots exist and 1 == 1, so Python continues across the and-chain to the left pair. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does matching roots and left subtrees not compensate for A's node 3 facing B's null child?
Full interview answer 10 min read

Determine whether two binary trees have identical shapes and equal values in every corresponding position.

Problem

Input. Two roots, first and second, of finite binary trees without cycles or shared children.

Output. Return True exactly when all corresponding node values and child positions match.

Rules. Compare structure as well as values; a left child does not match a right child. Values use Python ==. Nodes need not have the same object identities. Preserve both trees. Two empty trees match; exactly one empty tree does not.

Example. Root 1 with children 2 and 3 does not match root 1 with only left child 2. Their compact level-order notations are [1, 2, 3] and [1, 2, null]; return False.

Picture

Place the two roots together, then compare their corresponding child positions. Roots 1/1 pass; left children 2/2 and their missing children pass. Right pair 3/None fails, so the complete comparison fails.

Problem trace

Separate equal-value trees: corresponding child positions still differ

Worked example: equal values in different child positions are not the same treeBoth trees visit values 1 then 2 in preorder without null markers. Their left and right shapes differ, so structural equality is false.Child positions and missing childrenbelong to the structureTree A: two is on the left12#Value preorder: 1,2.Tree B: two is on the right1#2Value preorder: 1,2.
Read it this way: Both trees visit values 1 then 2 in preorder without null markers. Their left and right shapes differ, so structural equality is false. Can the same values-only preorder distinguish these left-child and right-child trees?
Reference drawing

Problem trace

Matching values are insufficient when corresponding child structure differs

Worked example: equal values in different child positions are not the same treeBoth trees visit values 1 then 2 in preorder without null markers. Their left and right shapes differ, so structural equality is false.Child positions and missing childrenbelong to the structureTree A: two is on the left12#Value preorder: 1,2.Tree B: two is on the right1#2Value preorder: 1,2.
Execution trace
Input and goalCheck whether two binary trees have the same shape and values.
Pair the two rootsCompare A = [1,2,3] with B = [1,2,null]. Both roots exist and 1 == 1, so Python continues across the and-chain to the left pair.

Tree A

Tree B

callStack[(A:1,B:1)]checkboth real; 1 == 1
node A:1 = B:1
compare pair
call stack
[(A:1,B:1)]
check
both real; 1 == 1

Recognize it
Use paired DFS when equality, symmetry, or structural correspondence requires comparing both value and shape at the same tree positions rather than comparing traversed value sequences.
Keep true
same_tree(first, second) returns true exactly when the two subtrees rooted at that pair have identical shape and equal values at every corresponding node.
Reuse it
When comparing recursive structures, recurse on aligned pairs and make missing-object cases explicit before reading values; this transfers to mirror symmetry, subtree equality, and AST comparison.
Compare A = [1,2,3] with B = [1,2,null]. Both roots exist and 1 == 1, so Python continues across the and-chain to the left pair. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does matching roots and left subtrees not compensate for A's node 3 facing B's null child?
Read it this way: Both trees visit values 1 then 2 in preorder without null markers. Their left and right shapes differ, so structural equality is false. Can the same values-only preorder distinguish these left-child and right-child trees?

Each call answers one exact question: do the complete subtrees at these aligned roots match?

Handle missing nodes before reading values or child fields. Both missing succeeds; exactly one missing fails. For real nodes, require value equality and both child comparisons.

Code

def same_tree(first: TreeNode | None, second: TreeNode | None) -> bool:
   if first is None or second is None:
      return first is second
   return (
      first.val == second.val
      and same_tree(first.left, second.left)
      and same_tree(first.right, second.right)
   )

The and chain stops at its first failure: values, then left pair, then right pair. Worst-case time is in total input nodes, with stack space along compared paths. A mismatch can stop earlier; a deep chain can exceed Python’s recursion limit.

Failure Check

[1,2] and [1,null,2] have the same preorder values but different child positions. Separate allocations can still match; real-node identity is not required. Both empty trees match; only one empty tree does not. This recursion is not cyclic-graph equivalence.

Change the Alignment

New task: Check whether one tree is the mirror of the other.

Picture and change: Cross left/right pairings, while retaining every value and missing-node check.

def mirror_equal(first, second):
   if first is None or second is None:
      return first is second
   return (
      first.val == second.val
      and mirror_equal(first.left, second.right)
      and mirror_equal(first.right, second.left)
   )

Check: [1,2,3] and [1,3,2] pass mirror equality but fail ordinary equality. Neither input is mutated.

Use when: Correspondence is reflected, not position-for-position. This compares the mirror relation; it does not invert a tree.

Change the Compared Fields

New task: Compare shape only.

Picture and change: Remove value equality, but retain aligned child positions and missing-node cases.

def same_shape(first, second):
   if first is None or second is None:
      return first is second
   return same_shape(first.left, second.left) and same_shape(first.right, second.right)

Check: [1,2] and [9,8] pass. [1,2] and [1,null,2] still fail. Both variants retain the original worst-case time, stack and recursion-limit qualifications.

Use when: The specification declares value labels irrelevant.

Transfer Check

Why is first is second correct in the original missing-node branch?

Answer

At least one argument is None there. Identity succeeds only when both are None; it imposes no identity requirement on real nodes.