-
Notifications
You must be signed in to change notification settings - Fork 1
/
tree.py
137 lines (108 loc) · 2.66 KB
/
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
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
135
136
# coding: utf-8
# In[ ]:
class Node(object):
""""""
def __init__(self, data):
self.data = data
self.left = None
self.right = None
@property
def dleft(self):
if self.left is None:
return None
return self.left.data
@dleft.setter
def dleft(self, value):
self.left = None(data)
@property
def dright(self):
if self.right is None:
return None
return self.right.data
@dright.setter
def dright(self, value):
self.right = Node(value)
class Tree(object):
""""""
def __init__(self, root_data):
self.root = Node(root_data)
self.nodes = 1
@property
def root_node(self):
return self.root
def add(self, value):
cur_node = self.root
while cur_node:
if value > cur_node.data:
if cur_node.right == None:
cur_node.right = Node(value)
break
else:
cur_node = cur_node.right
else:
if cur_node.left == None:
cur_node.left = Node(value)
break
else:
cur_node = cur_node.left
self.nodes += 1
return
def print_inorder_reg(node):
if node is None:
return
print_inorder_reg(node.left)
#print ("Data: {}".format(node.data))
print_inorder_reg(node.right)
def print_inorder_gen(node):
if node is None:
return
for n in print_inorder_gen(node.left):
yield n
yield node.data
for n in print_inorder_gen(node.right):
yield n
def build_tree(slist):
"""
Build tree from a sorted list slist.
"""
siz = len(slist)
if siz == 0:
return None
if siz == 1:
return Tree(slist[0])
ix = int(siz/2)
t = Tree(slist[ix])
def build_tree_impl(l):
sz = len(l)
if sz == 0:
return
ix = int(sz/2)
t.add(l[ix])
fhalf = l[:ix]
shalf = l[ix+1 :]
build_tree_impl(fhalf)
build_tree_impl(shalf)
pass
build_tree_impl(slist[:ix])
build_tree_impl(slist[ix+1:])
return t
if __name__ == "__main__":
"""
t = Tree(5)
t.add(1)
t.add(6)
t.add(2)
t.add(7)
print_inorder(t.root_node)
"""
l = []
for i in range(0, 99999):
l.append(i)
t = build_tree(l)
print_inorder_reg(t.root_node)
"""
#Generator based
for i in print_inorder_gen(t.root_node):
pass
"""
pass