-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkey_binary_tree.py
More file actions
95 lines (83 loc) · 2.81 KB
/
key_binary_tree.py
File metadata and controls
95 lines (83 loc) · 2.81 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
from key_binary_node import KeyBinaryNode
from linkqueue import LinkQueue
from printtree import PrintTree
# tree's degree = 2
class KeyBinaryTree:
def __init__(self, root=None):
self.root = root
#DLR Data Left Right
@staticmethod
def preorder_traversal(tree, handle, end=id):
if tree.root:
handle(tree)
if tree.root.left:
KeyBinaryTree.preorder_traversal(KeyBinaryTree(tree.root.left), handle, end)
if tree.root.right:
KeyBinaryTree.preorder_traversal(KeyBinaryTree(tree.root.right), handle, end)
end(tree)
# LDR
@staticmethod
def inorder_traversal(tree, handle, end=id):
if tree.root:
if tree.root.left:
KeyBinaryTree.inorder_traversal(KeyBinaryTree(tree.root.left), handle, end)
handle(tree)
if tree.root.right:
KeyBinaryTree.inorder_traversal(KeyBinaryTree(tree.root.right), handle, end)
end(tree)
# LRD
@staticmethod
def postorder_traversal(tree, handle, end=id):
if tree.root:
if tree.root.left:
BinaryTree.postorder_traversal(BinaryTree(tree.root.left), handle, end)
if tree.root.right:
BinaryTree.postorder_traversal(BinaryTree(tree.root.right), handle, end)
handle(tree)
end(tree)
def print_line(self):
rst = []
def handle(tree):
rst.append(str(tree.root))
# LDR 中序遍历显示
self.inorder_traversal(self, handle)
rst = "binary tree => " + str(rst)
return rst
def print_tree(self):
rst = PrintTree(list_=self.level_traversal()).rst
return rst[:-1]
def level_traversal(self):
level = -1
list_ = []
def handle(tree):
nonlocal level
level += 1
# list_ = [(key,level),...]
list_.append((str(tree.root), level))
def end(tree):
nonlocal level
level -= 1
self.preorder_traversal(self, handle, end)
return list_
def __str__(self):
#return self.print_line()
return self.print_tree()
def add(self, key, item):
if not self.root:
self.root = KeyBinaryNode(key, item)
elif key < self.root.key:
if not self.root.left:
self.root.left = KeyBinaryNode(key, item)
return
KeyBinaryTree(self.root.left).add(key, item)
else:
if not self.root.right:
self.root.right = KeyBinaryNode(key, item)
return
KeyBinaryTree(self.root.right).add(key, item)
if __name__ == '__main__':
t = KeyBinaryTree()
t.add(3,4)
t.add(1,'a')
t.add(8,'hello')
print(t)