|
| 1 | +# Definition for a binary tree node. |
| 2 | +# class TreeNode(object): |
| 3 | +# def __init__(self, val=0, left=None, right=None): |
| 4 | +# self.val = val |
| 5 | +# self.left = left |
| 6 | +# self.right = right |
| 7 | +class Solution(object): |
| 8 | + """ |
| 9 | + Recursive |
| 10 | + |
| 11 | + Stats: O(n) time, O(1) space |
| 12 | + Runtime: 32 ms, faster than 7.14% of Python online submissions for Invert Binary Tree. |
| 13 | + Memory Usage: 12.7 MB, less than 50.80% of Python online submissions for Invert Binary Tree. |
| 14 | + """ |
| 15 | + def invertTree(self, root): |
| 16 | + """ |
| 17 | + :type root: TreeNode |
| 18 | + :rtype: TreeNode |
| 19 | + """ |
| 20 | + ### base case |
| 21 | + if root == None: |
| 22 | + return |
| 23 | + |
| 24 | + #swap the left & right children with each other |
| 25 | + root.left, root.right = root.right, root.left |
| 26 | + |
| 27 | + #now swap for other future generations |
| 28 | + self.invertTree(root.left) |
| 29 | + self.invertTree(root.right) |
| 30 | + |
| 31 | + return root |
| 32 | + |
| 33 | + """ |
| 34 | + Iterative |
| 35 | + |
| 36 | + Stats: O(n) time, O(1) space |
| 37 | + Runtime: 20 ms, faster than 61.22% of Python online submissions for Invert Binary Tree. |
| 38 | + Memory Usage: 12.7 MB, less than 54.22% of Python online submissions for Invert Binary Tree. |
| 39 | + """ |
| 40 | + def invertTree(self, root): |
| 41 | + """ |
| 42 | + :type root: TreeNode |
| 43 | + :rtype: TreeNode |
| 44 | + """ |
| 45 | + if not root: |
| 46 | + return None |
| 47 | + |
| 48 | + stack = deque() |
| 49 | + stack.append(root) |
| 50 | + |
| 51 | + while stack: |
| 52 | + node = stack.popleft() |
| 53 | + |
| 54 | + #swap the left & right children with each other |
| 55 | + node.left, node.right = node.right, node.left |
| 56 | + |
| 57 | + if node.left: |
| 58 | + stack.append(node.left) |
| 59 | + if node.right: |
| 60 | + stack.append(node.right) |
| 61 | + |
| 62 | + return root |
0 commit comments