100. Same Tree ๐
Last updated
Last updated
Difficulty: Easy
- Tags: Binary Tree
, DFS
, Recursion
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.
Have nodes with the same values.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
The number of nodes in both trees is in the range [0, 100]
.
-10โด <= Node.val <= 10โด
.
To determine if two trees are the same, compare the following for both trees:
Values of the current nodes.
Recursively check their left and right subtrees.
If both nodes are null
, the subtrees are identical, return true
.
If only one node is null
or their values are not equal, return false
.
Recursively compare the left and right subtrees of p
and q
.
If both recursive calls return true
, the trees are the same.
O(n), where n
is the minimum number of nodes in both trees. Each node is visited once.
O(h), where h
is the height of the tree (stack space for recursion).
Consider solving the problem iteratively using a stack or queue.
How would the solution change if the input was not binary trees but general trees?
You can find the full solution here