forked from JushuangQiao/Python-Offer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsix.py
100 lines (80 loc) · 2.09 KB
/
six.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
# coding=utf-8
"""
使用先序遍历和中序遍历的结果重建二叉树
"""
from collections import deque
class TreeNode(object):
"""
二叉树结点定义
"""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree(object):
"""
二叉树
"""
def __init__(self):
self.root = None
def bfs(self):
ret = []
queue = deque([self.root])
while queue:
node = queue.popleft()
if node:
ret.append(node.val)
queue.append(node.left)
queue.append(node.right)
return ret
def pre_traversal(self):
ret = []
def traversal(head):
if not head:
return
ret.append(head.val)
traversal(head.left)
traversal(head.right)
traversal(self.root)
return ret
def in_traversal(self):
ret = []
def traversal(head):
if not head:
return
traversal(head.left)
ret.append(head.val)
traversal(head.right)
traversal(self.root)
return ret
def post_traversal(self):
ret = []
def traversal(head):
if not head:
return
traversal(head.left)
traversal(head.right)
ret.append(head.val)
traversal(self.root)
return ret
def construct_tree(preorder=None, inorder=None):
"""
构建二叉树
"""
if not preorder or not inorder:
return None
index = inorder.index(preorder[0])
left = inorder[0:index]
right = inorder[index+1:]
root = TreeNode(preorder[0])
root.left = construct_tree(preorder[1:1+len(left)], left)
root.right = construct_tree(preorder[-len(right):], right)
return root
if __name__ == '__main__':
t = Tree()
root = construct_tree([1, 2, 4, 7, 3, 5, 6, 8], [4, 7, 2, 1, 5, 3, 8, 6])
t.root = root
print t.bfs()
print t.pre_traversal()
print t.in_traversal()
print t.post_traversal()