LeetCode #572: Subtree of Another Tree
https://leetcode.com/problems/subtree-of-another-tree/
To solve the LeetCode problem “Subtree of Another Tree”, we need to determine whether the given binary tree subRoot
is a subtree of the binary tree root
. Here are the steps to solve this problem using Python:
- We start by defining a helper function
validate(one, two)
which will check if the two treesone
andtwo
are identical by checking if their values are equal and if their left and right subtrees are also identical. If either of the trees is None, we check if both trees are None. - Next, we define a recursive function
helper(root)
which will recursively traverse theroot
binary tree to check if the givensubRoot
is a subtree of theroot
. We do this by recursively checking if the current node in theroot
tree is identical to the givensubRoot
tree by calling thevalidate(one, two)
function. If the current node is identical to thesubRoot
tree, we return True. If not, we recursively call thehelper(root.left)
andhelper(root.right)
functions until we reach the end of theroot
tree. - Finally, we call the
helper(root)
function from the main functionisSubtree(root, subRoot)
and return the result.
Here is the Python code to solve this problem:
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
def helper(root):
if not root:
return False
elif validate(root, subRoot):
return True
return helper(root.left) or helper(root.right)
def validate(one, two):
if not one or not two:
return not one and not two
return one.val == two.val and validate(one.left, two.left) and validate(one.right, two.right)
return helper(root)
The time complexity of this solution is O(m * n) where m and n are the number of nodes in the root
and subRoot
trees respectively. This is because for each node in the root
tree, we traverse the subRoot
tree to check if it is identical to the current node in the root
tree. The space complexity of this solution is O(max(m, n)) as it uses the call stack to store the recursive function calls.