nathanwailes

Binary tree - Mirror/Invert

Apr 1st, 2024 (edited)
1,076
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. """
  2. https://leetcode.com/problems/invert-binary-tree/description/
  3.  
  4. Mirror/Invert a binary tree
  5.  
  6. The way to solve this is to think, "Ok, I just need to do a BFS/DFS on the tree and swap the left and right as I go." So, you need to already know how to do a BFS/DFS.
  7. """
  8.  
  9. # Recursive, using Vertex objects
  10.  
  11. class V:  # Vertex
  12.     def __init__(self, value=0, left=None, right=None):
  13.         self.value = value
  14.         self.left = left
  15.         self.right = right
  16.  
  17. def invert(root):
  18.     if root is None:
  19.         return
  20.     root.left, root.right = root.right, root.left
  21.     invert(root.left)
  22.     invert(root.right)
  23.  
  24.  
  25. root = V(1)
  26. root.left = V(2, V(4), V(5))
  27. root.right = V(3, V(6), V(7))
  28.  
  29. assert(root.left.left.value == 4)
  30. invert(root)
  31. assert(root.left.left.value == 7)
  32.  
  33.  
  34.  
  35. ###### Iterative implementation:
  36.  
  37. def invert(graph, head):
  38.     stack = [head]
  39.    
  40.     while stack:
  41.         curr = stack.pop()
  42.         if curr is None:
  43.             continue
  44.         curr.left, curr.right = curr.right, curr.left
  45.         stack.extend([curr.left, curr.right])
  46.  
  47.  
Advertisement
Add Comment
Please, Sign In to add comment