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.
Example 1:
Input: p = [1,2,3], q = [1,2,3] Output: true
Example 2:
Input: p = [1,2], q = [1,null,2] Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2] Output: false
Constraints:
[0, 100]
.-104 <= Node.val <= 104
The problem asks to determine if two given binary trees are structurally identical and have the same node values. Two approaches are presented: Depth-First Search (DFS) and Breadth-First Search (BFS).
This solution employs a recursive DFS approach. The core logic is:
Base Cases:
p
and q
are null
(empty), they are the same, return true
.null
and the other isn't, they are different, return false
.p.val
and q.val
) are different, they are different, return false
.Recursive Step: If the base cases are passed, recursively check if the left subtrees (p.left
, q.left
) are the same and if the right subtrees (p.right
, q.right
) are the same. The entire trees are identical only if both recursive calls return true
.
This solution uses an iterative BFS approach with queues.
Initialization: Create two queues, q1
and q2
, and add the root nodes of p
and q
respectively.
Iteration: While both queues are not empty:
a
and b
from q1
and q2
.a.val
and b.val
differ, return false
.a
and b
are consistently null
or not null
. If there's an inconsistency, return false
.a.left
and b.left
) are not null
, enqueue them.a.right
and b.right
) are not null
, enqueue them.Result: If the loop completes without returning false
, it means all nodes were compared and the trees are identical; return true
.
Both DFS and BFS offer the same time and space complexity for this problem. The choice often depends on personal preference or specific constraints of the input trees. DFS might be slightly more concise in code, while BFS might be preferable when dealing with extremely wide trees where stack overflow could be a concern in a recursive DFS implementation.