Same Tree
Master this topic with zero to advance depth.
Same Tree
Given roots of two trees p and q, check if they are the same.
Examples
Input: p = [1,2,3], q = [1,2,3]
Output: true
Approach 1
Level I: Recursive DFS
Intuition
Two trees are identical if their roots match and their respective subtrees are identical.
Diagram
(1) p.val == q.val?
(2) isSameTree(p.left, q.left)
(3) isSameTree(p.right, q.right)⏱ O(N)💾 O(H)
Detailed Dry Run
p(1), q(1) -> match. Recurse(2,2) -> match. Recurse(3,3) -> match. Result = true.
Approach 2
Level III: Iterative BFS (Parallel Queue)
Intuition
Use a queue to process pairs of nodes from both trees. If any pair differs, trees are not identical.
⏱ O(N)💾 O(W)
Detailed Dry Run
Queue: [(p, q)]. Pop, compare. Push children pairs. Any mismatch -> false.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.