-
Notifications
You must be signed in to change notification settings - Fork 2
/
00226-invert_binary_tree.py
79 lines (65 loc) · 2.02 KB
/
00226-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
# 226: Invert Binary Tree
# https://leetcode.com/problems/invert-binary-tree/
class TreeNode:
def __init__(self, x: int):
self.val = x
self.left = None
self.right = None
class Tree:
def __init__(self) -> None:
self.root = None
def creator(self, values: list[int], root: TreeNode, i: int, n: int) -> TreeNode:
if n==0 : return None
if i<n:
temp = TreeNode(values[i])
root = temp
root.left = self.creator(values, root.left, 2*i+1, n)
root.right = self.creator(values, root.right, 2*i+2, n)
return root
def createTree(self, inputs: list[int]) -> None:
self.root = self.creator(inputs, self.root, 0, len(inputs))
def showTree(self, root: TreeNode) -> None:
q = []
result = [[]]
c = []
if root==None : return result
q.append(root)
q.append(None)
while len(q)!=0:
t = q.pop(0)
if t==None:
result.append(c)
c = []
if len(q) > 0 : q.append(None)
else:
c.append(t.val)
if t.left!=None : q.append(t.left)
if t.right!=None : q.append(t.right)
print("[", end="")
for x in result:
if len(x)==0 : continue
print("[", end="")
for y in x:
if y==None:
print("NULL,", end="")
continue
print(y, end=",")
print("\b]", end=",")
print("\b]")
class Solution:
# SOLUTION
def invertTree(self, root: TreeNode) -> TreeNode:
if not root: return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
if __name__ == "__main__":
o = Solution()
tree = Tree()
# INPUT
tn = [4,2,7,1,3,6,9]
tree.createTree(tn)
# OUTPUT
result = o.invertTree(tree.root)
tree.showTree(result)