Same Tree
Same Tree
You are given the roots of two binary trees, p
and q
. Your task is to determine whether the two trees are the same.
Two binary trees are considered the same if they are structurally identical and the nodes have the same values.
Example
Input:
Output:
Constraints
-
The number of nodes in both trees is in the range
[0, 100]
. -
-10^4 <= Node.val <= 10^4
Trees are already built using the classic TreeNode class.
We just need:
-
A recursive function to traverse both trees in parallel.
Different Approaches
Approach 1: Recursive (Depth-First Search)
We traverse both trees simultaneously using recursion. At every node, we compare the values and recursively compare the left and right subtrees.
Approach 2: Iterative (Using Queue)
We perform a simultaneous level-order traversal (BFS) using a queue. At each step, we compare the current pair of nodes, and enqueue their children for further comparison.
Comments
Post a Comment