Statementâ–¼
Given the roots of two binary trees, p
and q
, write a function to check whether or not they are the same. Two binary trees are considered the same if they’re structurally identical and the nodes have the same value.
Constraints:
-
The number of nodes in the tree is in the range [0,100]
-
−104≤
node.data
≤104
Solution
To check whether or not two binary trees are identical, we will use a recursive approach called Depth-First Search (DFS). The function takes two trees with nodes, p
and q
, as input, and returns TRUE if they are identical and FALSE otherwise.
We’ll start by handling base cases. When both p
and q
are NULL, indicating they are identical, we return TRUE. If one of them is NULL and the other is not, they cannot be identical, so we will return FALSE.
Next, we will check if the values of the current nodes, p
and q
, are equal. If not, the trees are not identical, so we will return FALSE. Otherwise, we will recursively check if the left and right subtrees of p
and q
are also identical. If both subtrees are identical, we will return TRUE. Otherwise, FALSE will be returned.
In summary, the function uses Depth-First Search (DFS) to traverse the trees and check whether or not they are identical by comparing the values of their nodes and their left and right subtrees recursively.
Let’s look at the following illustration to get a better understanding of the solution: