Same tree checked with simultaneous DFS and the correct null check order in Java, Python and Rust

LeetCode 100 Same Tree – Null Checks in Java, Python, Rust

Day 35 of the Tekraze DSA series is Same Tree, which is LeetCode 100. The working solution is only four lines, yet it is one of the easiest problems to get subtly wrong. Swap two of those lines and the code crashes, or it tells you that two empty trees are different. Try to be clever and compare the trees as strings, and it can say two different trees are the same. So today the whole post is about those traps, with the real wrong outputs we got on the box, and why walking both trees at the same time avoids all of them.

What does the Same Tree problem ask?

You are given the roots of two binary trees, p and q. Return true if they are the same tree, meaning they have exactly the same shape and every matching pair of nodes holds the same value. Otherwise return false.

Input:  p = [1, 2, 3],  q = [1, 2, 3]
Output: true

    1         1
   / \       / \
  2   3     2   3

Input:  p = [1, 2],  q = [1, null, 2]
Output: false

    1         1
   /           \
  2             2

Input:  p = [1, 2, 1],  q = [1, 1, 2]   Output: false

The second example is the important one. Both trees hold the values 1 and 2, but the 2 hangs on the left in one tree and on the right in the other, so the shapes differ. Each tree has at most 100 nodes. If the bracket notation is new to you, the trees and graphs explained helper shows how a level order list maps onto a drawn tree.

How does simultaneous DFS compare two trees?

Instead of looking at each tree on its own, we walk both of them together, one pair of nodes at a time. At every pair there are only four possible situations, and the order in which we check them is the whole trick.

  • Both nodes are empty. Nothing left to compare on this branch, so it matches. Return true.
  • Exactly one node is empty. One tree has a node where the other has nothing, so the shapes differ. Return false.
  • Both exist but the values differ. Return false.
  • Both exist with the same value. The answer is true only if the left pair matches and the right pair matches, so recurse on both.

Because the two null checks run first, by the time we read p.val and q.val we already know both nodes exist. And because the recursion uses &&, it stops at the very first difference instead of exploring the rest of the trees. If recursion still feels like magic, the recursion explained helper walks through the call stack with pictures.

Why does the order of the null checks matter?

These are the two most common ways people break the order. We ran both on the box, and this is exactly what came back.

values first: [1, 2] vs [1, 2] -> AttributeError: 'NoneType' object has no attribute 'val'
or check first: [1, 2] vs [1, 2] -> False
or check first: [] vs [] -> False
  • Comparing values before checking for null. Two identical trees [1, 2] still crash, because the walk eventually reaches the empty right children and asks an empty node for its value. Python raises an AttributeError and Java throws a NullPointerException. The bug hides on tiny tests where every node has two children, then shows up on the first lopsided tree.
  • Putting the “one is null” check before the “both are null” check. The condition p == null || q == null is also true when both are empty, so it returns false before the “both empty” line ever runs. That line becomes dead code, and every pair of identical trees, including two empty ones, comes out as false.

A simple way to remember it is to go from the narrowest case to the widest. Both empty first, then either empty, then values, then children.

Can you just serialize both trees and compare the strings?

Yes, and it is a fair idea, but only if the serialization is done carefully. Two shortcuts look fine and quietly give wrong answers. Here is the real output for both, plus the fixed version.

preorder, no null markers: [1, 2] vs [1, None, 2] -> True
null markers, no separator: [1, 23] vs [12, 3] -> True
no separator strings: 123### 123###
markers and separators: [1, 2] vs [1, None, 2] -> False
markers and separators: [1, 23] vs [12, 3] -> False
  • Skipping empty children. A plain preorder walk gives 1,2 for both [1, 2] and [1, null, 2], so the shapes vanish and the answer is a wrong true. You must write a marker such as # for every missing child.
  • Leaving out separators. With null markers but no commas, [1, 23] and [12, 3] both become 123###. Multi digit values blur together, so you need a separator between values.
  • Doing it right. With both null markers and separators, the strings are unique for each tree and the comparison is correct. It still costs O(n) extra memory for the two strings and always walks both trees to the end, even when the roots already differ.

That is why simultaneous DFS is the answer interviewers expect. It needs no extra strings, has no encoding rules to get wrong, and returns as soon as it finds the first mismatch. Serialization is still worth knowing, because it becomes the core idea in Subtree of Another Tree and in serialize and deserialize problems.

What is the time and space complexity?

Time is O(n), where n is the number of nodes in the smaller tree, since we stop as soon as one side runs out or a value differs. Space is O(h) for the recursion stack, where h is the height. That is about log n for a balanced tree and n for a tree shaped like a chain. The iterative version below uses a queue of pairs instead, which holds up to one level of the tree at a time. If these terms feel fuzzy, the Big O helper post on time and space complexity explains them with simple examples.

Same Tree in Java

import java.util.*;

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) { this.val = val; }
}

class Solution {
    // Simultaneous DFS: walk both trees together and stop at the first difference
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;   // both empty, this branch matches
        if (p == null || q == null) return false;  // only one is empty, shapes differ
        if (p.val != q.val) return false;          // safe now, both nodes exist
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    // Iterative version: a queue of node pairs, no recursion depth limit
    public boolean isSameTreeIterative(TreeNode p, TreeNode q) {
        Deque<TreeNode[]> pairs = new ArrayDeque<>();
        pairs.add(new TreeNode[]{p, q});
        while (!pairs.isEmpty()) {
            TreeNode[] pair = pairs.poll();
            TreeNode a = pair[0], b = pair[1];
            if (a == null && b == null) continue;
            if (a == null || b == null || a.val != b.val) return false;
            pairs.add(new TreeNode[]{a.left, b.left});
            pairs.add(new TreeNode[]{a.right, b.right});
        }
        return true;
    }
}

The iterative method stores each pair as a two element array in an ArrayDeque. Note that ArrayDeque accepts arrays holding null, it just cannot store a bare null, so wrapping the pair keeps it safe.

Same Tree in Python

from typing import Optional
from collections import deque


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    # Simultaneous DFS: walk both trees together and stop at the first difference
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if p is None and q is None:   # both empty, this branch matches
            return True
        if p is None or q is None:    # only one is empty, shapes differ
            return False
        if p.val != q.val:            # safe now, both nodes exist
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

    # Iterative version: a queue of node pairs, no recursion depth limit
    def isSameTreeIterative(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        pairs = deque([(p, q)])
        while pairs:
            a, b = pairs.popleft()
            if a is None and b is None:
                continue
            if a is None or b is None or a.val != b.val:
                return False
            pairs.append((a.left, b.left))
            pairs.append((a.right, b.right))
        return True

Python uses is None for the checks, which is the idiomatic way to test for an empty node. The iterative version uses deque so popping from the front is O(1).

Same Tree in Rust

use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;

#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    pub fn new(val: i32) -> Self {
        TreeNode { val, left: None, right: None }
    }
}

struct Solution;

impl Solution {
    // Simultaneous DFS: match on both nodes at once, so a None can never be read
    pub fn is_same_tree(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
        match (p, q) {
            (None, None) => true,
            (Some(a), Some(b)) => {
                let (a, b) = (a.borrow(), b.borrow());
                a.val == b.val
                    && Self::is_same_tree(a.left.clone(), b.left.clone())
                    && Self::is_same_tree(a.right.clone(), b.right.clone())
            }
            _ => false, // only one side is empty
        }
    }

    // Iterative version: a queue of node pairs, no recursion depth limit
    pub fn is_same_tree_iterative(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
        let mut pairs = VecDeque::from(vec![(p, q)]);
        while let Some(pair) = pairs.pop_front() {
            match pair {
                (None, None) => continue,
                (Some(a), Some(b)) => {
                    let (a, b) = (a.borrow(), b.borrow());
                    if a.val != b.val { return false; }
                    pairs.push_back((a.left.clone(), b.left.clone()));
                    pairs.push_back((a.right.clone(), b.right.clone()));
                }
                _ => return false,
            }
        }
        true
    }
}

Rust makes the null check order mistake impossible. Matching on the tuple (p, q) forces you to handle both empty, both present and the mixed case, and the compiler will not let you read a value from a node that might be None.

We ran all three languages on the box before writing this. Both the recursive and iterative versions were checked on eight pairs, including [1, 2] against [1, null, 2], two empty trees, an empty tree against a single node and [1, 23] against [12, 3]. Python also cross checked both versions against a correct serialization on 300 random tree pairs. Every test passed.

Which earlier posts in the series should you read?

If you are new here, start with Day 1, Two Sum and Day 2, Best Time to Buy and Sell Stock. Day 13, Valid Parentheses and Day 14, Min Stack show how a stack works, which is what the recursion is using behind the scenes, and Day 17, Implement Queue using Stacks shows the queue idea used by the iterative version. Trees are linked nodes, so Day 18, Reverse Linked List and Day 19, Merge Two Sorted Lists are good warm ups, and comparing two lists node by node in Merge Two Sorted Lists is very close to comparing two trees. Day 23, Binary Search covers binary search, which comes back with binary search trees. For more tree practice try Day 34, Maximum Depth of Binary Tree. Recursion was the main tool in Day 29, Permutations. For binary search practice try Day 25, Koko Eating Bananas, Day 26, Find Minimum in Rotated Sorted Array, Day 27, Search in Rotated Sorted Array. The data structures cheat sheet is a handy one page summary.

Frequently asked questions

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

Walk both trees together. If both nodes are empty return true, if only one is empty return false, if the values differ return false, otherwise check the left pair and the right pair recursively.

Why does my Same Tree solution throw a null pointer error?

You are probably reading the node values before checking whether the nodes exist. Check that both nodes are null first, then that either one is null, and only then compare the values.

Can I compare two trees by converting them to strings?

Yes, but the string must include a marker for every empty child and a separator between values. Without markers, trees like [1, 2] and [1, null, 2] look the same, and without separators [1, 23] and [12, 3] collide.

What is the time and space complexity of Same Tree?

Time is O(n) because each pair of nodes is compared at most once. Space is O(h) for the recursion stack, where h is the tree height, which is O(log n) for a balanced tree and O(n) for a skewed one.

Is Same Tree the same as Symmetric Tree?

They are close cousins. Same Tree compares left with left and right with right across two trees, while Symmetric Tree compares one tree with its own mirror, so it pairs the left child of one side with the right child of the other.

Content Protection by DMCA.com
Spread the love
Scroll to Top
×