forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
invert-binary-tree.py
100 lines (84 loc) · 2.15 KB
/
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# Time: O(n)
# Space: O(h)
#
# Invert a binary tree.
#
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
# to
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
#
# Time: O(n)
# Space: O(w), w is the max number of the nodes of the levels.
import collections
# BFS solution.
class Queue:
def __init__(self):
self.data = collections.deque()
def push(self, x):
self.data.append(x)
def peek(self):
return self.data[0]
def pop(self):
return self.data.popleft()
def size(self):
return len(self.data)
def empty(self):
return len(self.data) == 0
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if root is not None:
nodes = Queue()
nodes.push(root)
while not nodes.empty():
node = nodes.pop()
node.left, node.right = node.right, node.left
if node.left is not None:
nodes.push(node.left)
if node.right is not None:
nodes.push(node.right)
return root
# Time: O(n)
# Space: O(h)
# Stack solution.
class Solution2:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if root is not None:
nodes = []
nodes.append(root)
while nodes:
node = nodes.pop()
node.left, node.right = node.right, node.left
if node.left is not None:
nodes.append(node.left)
if node.right is not None:
nodes.append(node.right)
return root
# Time: O(n)
# Space: O(h)
# DFS, Recursive solution.
class Solution3:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if root is not None:
root.left, root.right = self.invertTree(root.right), \
self.invertTree(root.left)
return root