nathanwailes

Binary tree - Are two trees the same

Sep 9th, 2024
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. """
  2. Idea: Do a BFS where each entry in the queue is a pair of ndoes, return False if at any point the two nodes in the current entry don't have the same value.
  3. """
  4.  
  5.  
  6. # Recursive solution:
  7.  
  8. class Solution:
  9.     def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
  10.         if not p and not q:
  11.             return True
  12.         elif not q or not p:
  13.             return False
  14.         elif p.val != q.val:
  15.             return False
  16.         return self.isSameTree(p.right, q.right) and self.isSameTree(p.left, q.left)
  17.  
  18.  
  19. # Iterative solution:
  20.  
  21. from collections import deque
  22. class Solution:
  23.     def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
  24.         queue = deque([(p, q)])
  25.         while queue:
  26.             p, q = queue.popleft()
  27.             if (p and not q) or (q and not p):
  28.                 return False
  29.             if p and q:
  30.                 if p.val != q.val:
  31.                     return False
  32.                 queue.append((p.left, q.left))
  33.                 queue.append((p.right, q.right))
  34.  
  35.         return True
  36.  
Advertisement
Add Comment
Please, Sign In to add comment