Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. # O(n) time | O(d) space
  2. def invertBinaryTree(tree):
  3. if tree is None:
  4. return 0
  5. (tree.left, tree.right) = (tree.right, tree.left)
  6. if tree.left:
  7. invertBinaryTree(tree.left)
  8. if tree.right:
  9. invertBinaryTree(tree.right)
  10.  
  11. # O(n) time | O(n) space
  12. def invertBinaryTree(tree):
  13. queue = [tree]
  14. while len(queue):
  15. current = queue.pop(0)
  16. if current is None:
  17. continue
  18. tree.left, tree.right = tree.right, tree.left
  19. queue.append(current.left)
  20. queue.append(current.right)
  21.  
  22. def isSameTree(self, p, q):
  23. if p or q is None:
  24. return False
  25. if p and q is None:
  26. return True
  27. if p != q:
  28. return False
  29. self.isSameTree(p.left, q.left)
  30. self.isSameTree(p.right, q.right)
  31.  
  32. def isSymmetric(self, root):
  33. if root is None:
  34. return 0
  35. return self._isSymmetric(root.left, root.right)
  36.  
  37. def _isSymmetric(self, left, root):
  38. if left or right is None:
  39. return False
  40. if left and right is None:
  41. return True
  42. if left.val == right.val:
  43. isSameChildNode1 = self._isSymmetric(left.left, right.right)
  44. isSameChildNode2 = self._isSymmetric(left.right, right.left)
  45. else:
  46. return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement