-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree
More file actions
99 lines (85 loc) · 2.29 KB
/
Copy pathBinaryTree
File metadata and controls
99 lines (85 loc) · 2.29 KB
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
class TreeNode():
def __init__(self, elem = None, lchild = None, rchild = None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
class Tree():
def __init__(self):
self.root = None
def add(self, elem):
new_node = TreeNode(elem)
if self.root is None:
self.root = new_node
else:
myQueue = [self.root]
while True:
cur = myQueue.pop(0)
if cur.lchild is None:
cur.lchild = new_node
break
elif cur.rchild is None:
cur.rchild = new_node
break
else:
myQueue.append(cur.lchild)
myQueue.append(cur.rchild)
def preOrderRecur(root):
if root is None:
return
myStack = [root]
while myStack:
cur = myStack.pop()
print(cur.elem, end = ' ')
if cur.rchild:
myStack.append(cur.rchild)
if cur.lchild:
myStack.append(cur.lchild)
print('')
def preOrder(root):
if root:
print(root.elem, end = ' ')
preOrder(root.lchild)
preOrder(root.rchild)
def inOrderRecur(root):
if root:
cur = root
myStack = []
while myStack or cur:
if cur:
myStack.append(cur)
cur = cur.lchild
else:
cur = myStack.pop()
print(cur.elem, end = ' ')
cur = cur.rchild
print('')
def inOrder(root):
if root:
inOrder(root.lchild)
print(root.elem, end = ' ')
inOrder(root.rchild)
def posOrderRecur(root):
if root:
myStack = [root]
resStack = []
while myStack:
cur = myStack.pop()
resStack.append(cur.elem)
if cur.lchild:
myStack.append(cur.lchild)
if cur.rchild:
myStack.append(cur.rchild)
for each in resStack[::-1]:
print(each, end = ' ')
print('')
def posOrder(root):
if root:
posOrder(root.lchild)
posOrder(root.rchild)
print(root.elem, end = ' ')
t1 = Tree()
for i in range(1, 8):
t1.add(i)
posOrder(t1.root)
print('')
posOrderRecur(t1.root)