Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- https://leetcode.com/problems/invert-binary-tree/description/
- Mirror/Invert a binary tree
- 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.
- """
- # Recursive, using Vertex objects
- class V: # Vertex
- def __init__(self, value=0, left=None, right=None):
- self.value = value
- self.left = left
- self.right = right
- def invert(root):
- if root is None:
- return
- root.left, root.right = root.right, root.left
- invert(root.left)
- invert(root.right)
- root = V(1)
- root.left = V(2, V(4), V(5))
- root.right = V(3, V(6), V(7))
- assert(root.left.left.value == 4)
- invert(root)
- assert(root.left.left.value == 7)
- ###### Iterative implementation:
- def invert(graph, head):
- stack = [head]
- while stack:
- curr = stack.pop()
- if curr is None:
- continue
- curr.left, curr.right = curr.right, curr.left
- stack.extend([curr.left, curr.right])
Advertisement
Add Comment
Please, Sign In to add comment