AAlgoLoopSpaced repetition for LeetCode
EASYTree / RecursionLeetCode ↗

Same Tree

The key idea

Two trees are the same only if their roots match in value AND their left subtrees are the same AND their right subtrees are the same. Recurse on the two trees in lockstep, comparing the matching nodes; the moment a value differs or one node exists where the other is null, they are not the same.

Problem

You are given the roots of two binary trees p and q. Write a function to check whether the two trees are the same.

Two binary trees are considered the same when they are structurally identical and every pair of matching nodes holds the same value. That means a node that exists in one tree must exist at the very same position in the other, and the two nodes there must carry equal values.

Return true if the trees are the same, and false otherwise.

Constraints

Examples

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

Complexity

Time: O(n) Space: O(h)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems