Same Tree
Given the roots of two binary trees p
and q
, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

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
Approach 1: Recursion
Intuition
The simplest strategy here is to use recursion. Check if p
and q
nodes are not None
, and their values are equal. If all checks are OK, do the same for the child nodes recursively.
Approach 2: Iteration
Intuition
Start from the root and then at each iteration pop the current node out of the queue. Then do the same checks as in the approach 1 :
p
andp
are notNull
p.val
is equal toq.val
and if checks are OK, push the child nodes.
Complexity Analysis
- Time complexity : O(N) since each node is visited exactly once.
- Space complexity : O(log(N)) in the best case of completely balanced tree and O(N) in the worst case of completely unbalanced tree, to keep a queue.