Question
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.
This is atree question.
Idea(s)
- Use the solution from Leetcode - Subtree of Another Tree to get a list of both tree nodes
- Use a subarray of array algorithm to check if the subtree array is a subarray of the main tree array
- You can also solve the “same tree” problem recursively
- Check if p and q exist
- If they are the same value
- recursively check same tree on left and right children
- Else return false
- Then you can dfs down the two trees until a subtree of the main tree is the same tree as the subtree using the sameTree function (ex here)