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