Subtree of Another Tree
TreeDFSRecursion
Problem Statement
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
Example
Example 1:
root:
subRoot:
Output: true
Constraints
- The number of nodes in the roottree is in the range [1, 2000].
- The number of nodes in the subRoottree is in the range [1, 1000].
- -104 ≤ root.val ≤ 104
- -104 ≤ subRoot.val ≤ 104
Solution (DFS)
The solution uses a Depth-First Search (DFS) to traverse the main tree. For each node in the main tree, we check if the subtree rooted at that node is identical to the subRoot tree.
Algorithm Steps
- Traverse the roottree.
- For each node in root, check if the subtree rooted at that node is the same as thesubRoottree.
- To check if two trees are the same, we can use a helper function that recursively compares the nodes of the two trees.
- If we find a matching subtree, we return true.
- If we traverse the entire roottree and don't find a matching subtree, we returnfalse.
Start: Check if subRoot is a subtree of root.
Subtree of Another Tree Solution