Advertisement
Guest User

Untitled

a guest
Oct 24th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. #
  2. # Binary trees are already defined with this interface:
  3. # class Tree(object):
  4. # def __init__(self, x):
  5. # self.value = x
  6. # self.left = None
  7. # self.right = None
  8. def isSubtree(t1, t2):
  9. def isEqual(left, right):
  10. if left == None and right == None:
  11. return True
  12. if right == None and left != None:
  13. return False
  14. if left == None and right != None:
  15. return False
  16.  
  17. return left.value == right.value and isEqual(left.right, right.right) and isEqual(left.left, right.left)
  18.  
  19.  
  20. # Base Case
  21. if t2 is None:
  22. return True
  23.  
  24. if t1 is None:
  25. return False
  26.  
  27. # Check the tree with root as current node
  28. if isEqual(t1, t2):
  29. return True
  30.  
  31. # IF the tree with root as current node doesn't match
  32. # then try left and right subtreee one by one
  33. return isSubtree(t1.left, t2) or isSubtree(t1.right, t2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement