Statementâ–¼
Given the roots of two binary trees, root
and sub_root
, return TRUE if there is a subtree of root
with the same structure and nodes as sub_root
. Otherwise, return FALSE.
A tree can only be considered a subtree of the root
tree iff all the descendants (children) of the node appear in sub_root
.
Constraints:
The number of nodes in the
root
tree is in the range[1,500]. The number of nodes in the
sub_root
tree is in the range[1,250]. −104≤ root.data
≤104 −104≤ sub_root.data
≤104
Solution
We need to check if there exists a subtree in the root
binary tree such that all the descendants and the root node itself match the sub_root
binary tree. To explore and traverse the binary trees, we'll have to use the depth-first search approach and check each node of the trees. We'll first traverse over the left subtree and then the right subtree of the root
binary tree, while comparing the values of the nodes with the sub_root
binary tree.
Here is how we’ll implement this algorithm:
Starting from the root node of both binary trees:
We'll check for any identical node in both trees. If any identical value is found, we then move downward and traverse the left and right subtrees of both trees to compare their children nodes.
If any identical value is not found, then we'll keep traversing over the left and right subtree of the
root
binary tree until we've reached the last leaf node.We'll return TRUE, if any identical value is found. Otherwise we return FALSE.
Here’s the demonstration of the steps above: