Subtree of Another Tree (Leetcode 572) [Optimisation required]
Problem Link: https://leetcode.com/problems/subtree-of-another-tree/
class Solution:
def similar(root1, root2):
if(root1 is None and root2 is None):
return True
elif(root1 is None and root2 is not None):
return False
elif(root1 is not None and root2 is None):
return False
else:
if(root1.val == root2.val):
l=Solution.similar(root1.left,root2.left)
r=Solution.similar(root1.right,root2.right)
if(l and r):
return True
else:
return False
else:
return False
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if(root is None):
return
if(root.val==subRoot.val):
if(Solution.similar(root,subRoot)):
return True
l=self.isSubtree(root.left,subRoot)
r=self.isSubtree(root.right,subRoot)
if(l or r):
return True
return False
PreviousKth Smallest Element in a BST (Leetcode 230) [Optimisation Required]NextValidate Binary Search Tree(BST) (Leetcode 98)
Last updated