-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmybtree.py
135 lines (111 loc) · 3.33 KB
/
mybtree.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class Node(object):
def __init__(self, value=None, lchild=None, rchild=None):
self.value = value
self.lchild = lchild
self.rchild = rchild
class Btree(object):
def __init__(self):
self.root = None
def append(self, value):
node = Node(value)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
curnode = queue.pop(0)
if curnode.lchild is None:
curnode.lchild = node
return
else:
queue.append(curnode.lchild)
if curnode.rchild is None:
curnode.rchild = node
return
else:
queue.append(curnode.rchild)
def breadth_order(self):
queue = [self.root]
while queue:
curnode = queue.pop(0)
print(curnode.value, end=' ')
if curnode.lchild is not None:
queue.append(curnode.lchild)
if curnode.rchild is not None:
queue.append(curnode.rchild)
def DLR_recursion(self, node):
if node is None:
return
print(node.value, end=' ')
self.DLR_recursion(node.lchild)
self.DLR_recursion(node.rchild)
def LDR_recursion(self, node):
if node is None:
return
self.LDR_recursion(node.lchild)
print(node.value, end=' ')
self.LDR_recursion(node.rchild)
def LRD_recursion(self, node):
if node is None:
return
self.LRD_recursion(node.lchild)
self.LRD_recursion(node.rchild)
print(node.value, end=' ')
def DLR_no_recursive(self):
stack = []
curnode = self.root
while curnode or stack:
while curnode:
print(curnode.value, end=' ')
stack.append(curnode)
curnode = curnode.lchild
curnode = stack.pop()
curnode = curnode.rchild
def LDR_no_recursive(self):
stack = []
curnode = self.root
# stack_shadow = []
while curnode or stack:
while curnode:
stack.append(curnode)
curnode = curnode.lchild
curnode = stack.pop()
# stack_shadow.append(curnode)
print(curnode.value, end=' ')
curnode = curnode.rchild
def LRD_no_recursive(self):
stack = []
stack_shadow = []
curnode = self.root
while curnode or stack:
while curnode:
stack.append(curnode)
stack_shadow.append(curnode)
curnode = curnode.rchild
curnode = stack.pop()
curnode = curnode.lchild
return stack_shadow[::-1]
tree = Btree()
tree.append(1)
tree.append(2)
tree.append(3)
tree.append(4)
tree.append(5)
tree.append(6)
tree.append(7)
tree.breadth_order()
print('广度优先')
tree.DLR_recursion(tree.root)
print("先序遍历-递归")
tree.DLR_no_recursive()
print("先序遍历-非递归")
tree.LDR_recursion(tree.root)
print("中序遍历-递归")
tree.LDR_no_recursive()
print("中序遍历-非递归")
tree.LRD_recursion(tree.root)
print("后序遍历-递归")
lrdnode = tree.LRD_no_recursive()
for i in lrdnode:
print(i.value, end=' ')
print("后序遍历-非递归")