Problem
Given two binary trees, 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:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Explanation 1
-
We can use recursion method to solve this problem. If two tree are the same, then their
root.val
are the same, androot.left.val
are the same, androot.right.val
are the same. -
The base case is if two trees are NULL, then they are the same, else if one tree is NULL another is not NULL, then we return false.
Solution 1
1 |
|
Explanation 2
-
We can also use BFS (level-order traversal) to solve this problem. The difference is we can’t pop the nodes from both queue and compare them because in the problem’s Example 2, the second level have the same values
2
, but one of them is belongs to the left child, and another one belongs to the right child. So before we push the node into the queue, we need to compare both current nodes’ left childs and right childs. -
First, we make a helper function to compare 2 root nodes if they both are NULL or they both have the same value, then return true, else return false.
-
Initialize two queues
q1
to hold the TreeNodes for Treep
,q2
to hold the TreeNodes for Treeq
. Then, we push root nodep
toq1
and push root nodeq
toq2
. -
While both queue are not empty, we poll out the nodes
curP
andcurQ
from both queues. Then we pass their left childs to the helper function, and pass their right childs to the helper function to comparecurP.left
is the same ascurQ.left
, andcurP.right
is the same ascurQ.right
. If one of the helper function return false, we immediately return false. Else, we push their left child and right child to the queue. Repeat until one of the queue is empty. -
Outside the while loop, we can return true.
Solution 2
1 |
|