Same Tree

Structural recursion — both null OK; one null fails; equal values + recurse left and right.

Easy
Time O(n) Space O(n)
LeetCode
2 min read
tree dfs recursion

Problem#

Return true iff two binary trees are structurally identical and have the same node values.

Examples#

  • [1,2,3], [1,2,3]true.
  • [1,2], [1,null,2]false; [1,2,1], [1,1,2]false.

Constraints#

  • 0 <= nodes <= 100.

Approach#

Recursion: both null → equal; one null → not equal; values differ → not equal; else recurse on children.

Solution#

Same Tree
struct TreeNode { int val; TreeNode* left; TreeNode* right; };
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p && !q) return true;
if (!p || !q) return false;
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};

Editorial#

Three cases at every recursive call cover all possibilities for the pair. The order of the children matters — (left, left) and (right, right), not crosswise.

Complexity#

  • Time: O(n).
  • Space: O(h) recursion (worst-case O(n)).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.