AlgoInsight

DSA problem

Same Tree

EasyTree Traversal - Pre OrderPattern: Tree Traversal - Pre Ordertop300AmazonMicrosoftGoogleAppleBloomberg

Given the roots p and q of two binary trees, decide whether they are structurally identical and node-wise equal. The trees are considered the same when they have exactly the same shape and every corresponding pair of nodes carries the same value.

This is the canonical introductory tree problem because the recurrence is so clean. Two trees are the same iff: (1) both roots are null (vacuously equal), or (2) both roots are non-null, the values match, and the left subtrees are the same and the right subtrees are the same. Any other combination — one null and one non-null, or differing values — means the trees diverge.

The structure of the recurrence is preorder by design: you compare the current pair of roots before descending into their children, short-circuiting the recursion the moment a mismatch is found. This early termination matters in practice — for two random large trees, a difference is often found near the top.

The natural implementation is a four-line recursion. An iterative version using a stack (or queue) of pairs is equally O(n) time and works the same way; the recursive form is preferred for clarity unless you specifically need to avoid stack frames. Either way, time is O(n) where n is the size of the smaller tree once divergence is detected, and space is O(h) for the recursion stack.

Examples

Example 1
Input: p = [1,2,3], q = [1,2,3]
Output: true
Explanation: Both trees have a root of value 1, a left child of 2, and a right child of 3 — identical shape and identical values, so the answer is true.
Example 2
Input: p = [1,2], q = [1,null,2]
Output: false
Explanation: In tree p the node 2 is the left child of 1; in tree q the node 2 is the right child of 1. Same values but different shape, so the trees differ.
Example 3
Input: p = [1,2,1], q = [1,1,2]
Output: false
Explanation: The shape matches but the values at the left and right children are swapped, so the trees are not the same.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchrecursion

Browse all DSA problems