-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree_binary_search.py
458 lines (390 loc) · 11.2 KB
/
Tree_binary_search.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
import networkx as nx
import matplotlib.pyplot as plt
# Lets play with binary search tree
# - Define node
# - Define tree
# - def: get left, right, value
# - def: set left, right, value
# - Tree traversal
# - Tree insert nodes / build tree
# - Tree search
class Node:
def __init__(self,left,right,value):
self.left = left
self.right = right
self.value = value
def get_left(self):
return self.left
def get_right(self):
return self.right
def get_value(self):
return self.value
def set_value(self,value):
self.value = value
def set_left(self,value):
if value == None:
self.left = None
else:
self.left = Node(None,None,value)
def set_right(self,value):
if value == None:
self.right = None
else:
self.right = Node(None,None,value)
class Tree:
def __init__(self):
self.root = None
def insert_node(self,node,value):
# 1. Check if root is None if yes, assign value to root
# 2. If not, compare value with node value
# 3. If lower then check if left child exists
# 4. If not create it and give it new value
# 5. If it exists, do recursion on left child
# 6. Same for right child
if self.root == None:
self.root = Node(None,None,value)
else:
if value <= node.get_value():
if node.get_left() == None:
node.set_left(value)
else:
self.insert_node(node.get_left(),value)
else:
if node.get_right() == None:
node.set_right(value)
else:
self.insert_node(node.get_right(),value)
def search(self,value):
# 1. Check if tree is empty
# 2. While the node is not None
# 3. if you find value, return it
# 4. if you don't, traverse to left or right
# 5. if you don't find it in tree, say it
node = self.root
while node != None:
if node.get_value() == value:
return node
else:
if value < node.get_value():
node = node.get_left()
else:
node = node.get_right()
print "Value not found"
return None
def recursive_search(self,node,value):
# 1. Check if root is None
# 2. If not check if root value equals value
# 3. If yes, return it
# 4. If not, traverse right or left and return what you find
if node == None:
return None
else:
if node.get_value() == value:
#print "here",node.get_value()
return node
else:
if value < node.get_value():
return self.recursive_search(node.get_left(),value)
else:
return self.recursive_search(node.get_right(),value)
def find_max(self,node):
node = self.root
while node.get_right() != None:
node = node.get_right()
return node.get_value()
def find_min(self,node):
node = self.root
while node.get_left() != None:
node = node.get_left()
return node.get_value()
def find_parent_node(self,root,node):
# 1. Check if node is None
# 2. Check if node is root
# 3. check if any of the children of the root are equal to node
# 4. If none of the above, then depending on the value of the node
# recurse left or right
# 5. Before recursing, remember to check if left or right child exist
# if it does not, it means that the node is not from this tree!
# Check your tree
if node == None:
print "Node is None"
elif node == self.root:
print "This is a root which has no parent"
else:
parent = root
if (parent.get_left()!= None and parent.get_left() == node):
return [parent,"left"]
elif (parent.get_right()!= None and parent.get_right() == node):
return [parent,"right"]
else:
if node.get_value() < parent.get_value():
if parent.get_left() == None:
print "Can't find parent in this tree"
else:
return self.find_parent_node(parent.get_left(),node)
else:
if parent.get_right() == None:
print "Can't find parent in this tree"
else:
return self.find_parent_node(parent.get_right(),node)
def find_max_left(self,node):
# Largest value in left subtree below node
if node.get_left() == None:
return node
else:
node = node.get_left()
while node.get_right() != None:
node = node.get_right()
return node
def find_min_right(self,node):
# Largest value in left subtree below node
if node.get_right() == None:
print "No right node"
return node
else:
node = node.get_right()
while node.get_left() != None:
node = node.get_left()
return node
def isLeaf(self,node):
if node.get_left() == None and node.get_right() == None:
return True
else:
return False
def remove_leaf(self,node):
if self.root == None:
print "Tree is empty"
if self.isLeaf(node):
if node == self.root:
self.root = None
else:
parent = self.find_parent_node(self.root,node)
parent_node = parent[0]
child = parent[1]
if child == "left":
parent_node.set_left(None)
else:
parent_node.set_right(None)
else:
print "Error in remove leaf: Not a leaf"
def remove_node(self,node):
# For some info on removing the node see here:
# http://webdocs.cs.ualberta.ca/~holte/T26/del-from-bst.html
# I need 5 functions for the remove node to work
# - isLeaf
# - find_max_left
# - find_min_right
# - find_parent_node
# - remove_leaf
# When writing your finctions be careful with:
# - always check if tree is not empty
# - always check if your node to remove is root
# - check if the node to remove is not None!
# - check if leaf is root
# - check if left or right exists
# - be careful when renaming nodes
# - Also note that function find_parent_node returns a list of two elements!
if self.root == None:
print "Tree is empty"
elif node == None:
print "Nothing to remove"
elif self.isLeaf(node):
if node == self.root:
self.root = None
else:
self.remove_leaf(node)
else:
if node.get_left() != None:
maxnode = self.find_max_left(node)
if self.isLeaf(maxnode):
new_value = maxnode.get_value()
self.remove_leaf(maxnode)
node.set_value(new_value)
else:
node.set_value(maxnode.get_value())
self.remove_node(maxnode)
else:
maxnode = self.find_min_right(node)
if self.isLeaf(maxnode):
new_value = maxnode.get_value()
self.remove_leaf(maxnode)
node.set_value(new_value)
else:
node.set_value(maxnode.get_value())
self.remove_node(maxnode)
def tree_height(self,node):
# Height of a free is height of its highest tree + 1
if node == None:
return 0
else:
return 1 + max(self.tree_height(node.get_left()),self.tree_height(node.get_right()))
def lowest_common_ancestor(self,node,node1,node2):
# lowest common ancestor is always between node1 and node 2 values
# if node1 and node2 > current node, go right
# if node1 and node2 < current node, go left
# First one encountered is the lowest common node
# Lets assime n1 < n2
if node == None:
print "Tree is empty"
return None
elif node.get_value() > node1 and node.get_value() < node2:
return node.get_value()
elif node.get_value() == node1:
return node1
elif node.get_value() == node2:
return node2
elif node.get_value() < node1 and node.get_value() < node2:
return self.lowest_common_ancestor(node.get_right(),node1,node2)
elif node.get_value() > node1 and node.get_value() > node2:
return self.lowest_common_ancestor(node.get_left(),node1,node2)
# ---------------------------------------
# Non class functions
def traversal_preorder(node):
# 1. Check if tree is empty
# 2. If empty, give a message
# 3. If not empty, print value of the current node
# 4. If left child exists recurse/traverse to left
# 5. If right child exists recurse/traverse to right
if node == None:
print "Tree is empty"
else:
print node.get_value()
if (node.get_left() != None):
traversal_preorder(node.get_left())
if (node.get_right() != None):
traversal_preorder(node.get_right())
# This travelsal returns a sorted list of nodes
def traversal_inorder(node):
if node == None:
print "Tree is empty"
else:
if (node.get_left() != None):
traversal_inorder(node.get_left())
print node.get_value()
if (node.get_right() != None):
traversal_inorder(node.get_right())
def traversal_postorder(node):
if node == None:
print "Tree is empty"
else:
if (node.get_left() != None):
traversal_postorder(node.get_left())
if (node.get_right() != None):
traversal_postorder(node.get_right())
print node.get_value()
def preorder_without_recursion(node):
# For preorder I will use stack
print "Traverse preorder without recursion"
stack = []
if node == None:
print "Tree is empty"
return None
else:
current = node
while current != None or len(stack) > 0:
if current != None:
print current.get_value()
stack.append(current.get_right())
current = current.get_left()
else:
current = stack.pop()
def inorder_without_recursion(node):
print "Traverse inorder without recursion"
stack = []
if node == None:
print "Tree is empty"
return None
else:
current = node
while current != None or len(stack) > 0:
if current != None:
stack.append(current.get_right())
stack.append(current)
current = current.get_left()
else:
print stack.pop().get_value()
current = stack.pop()
# This function is not finished!!!!
# Can't figure out how to do it
def postorder_without_recursion(node):
print "Traverse postorder without recursion"
stack = []
if node == None:
print "Tree is empty"
return None
else:
current = node
while current != None or len(stack) > 0:
if current != None:
stack.append(current)
stack.append(current.get_right())
stack.append(current.get_left())
else:
current = stack.pop()
if current == None:
print stack.pop().get_value()
current = stack.pop()
# --------------------------
# Functions for testing tree codes!
def get_nodes(root,G):
if root != None:
G.add_node(root.get_value())
if (root.get_right() != None):
get_nodes(root.get_right(),G)
G.add_edge(root.get_value(),root.get_right().get_value())
if (root.get_left() != None):
get_nodes(root.get_left(),G)
G.add_edge(root.get_value(),root.get_left().get_value())
def plot_tree(root):
# http://stackoverflow.com/questions/11479624/is-there-a-way-to-guarantee-hierarchical-output-from-networkx
G = nx.DiGraph()
get_nodes(root,G)
if len(G.nodes())==0:
print "Tree is empty"
else:
pos=nx.graphviz_layout(G,prog='dot')
nx.draw(G,pos,with_labels=True,arrows=False,node_size=1000)
plt.show()
def build_tree(mylist):
if len(mylist) == 0:
print "List is empty"
return None
else:
t = Tree()
for l in mylist:
t.insert_node(t.root,l)
return [t,mylist]
def thisnode(tree,value):
return tree.recursive_search(tree.root,value)
def test_tree(tree):
nodes = tree[1]
for n in nodes:
print "remove",n
t = build_tree(nodes)
t[0].remove_node(thisnode(t[0],n))
# Node removal testing
t1 = build_tree([5])
t2 = build_tree([5,1])
t3 = build_tree([5,20])
t4 = build_tree([5,1,20])
t5 = build_tree([5,4,3,2])
t6 = build_tree([5,10,15,20])
t7 = build_tree([5,3,20,1,4,10,25])
t8 = build_tree([10,5,8,7,9])
t9 = build_tree([100,50, 150,25,75,125,175,110])
test_tree(t1)
test_tree(t2)
test_tree(t3)
test_tree(t4)
test_tree(t5)
test_tree(t6)
test_tree(t7)
test_tree(t8)
traversal_inorder(t7[0].root)
t = t9[0]
plot_tree(t.root)
print "height",t.tree_height(t.root)
inorder_without_recursion(t.root)
preorder_without_recursion(t.root)
#postorder_without_recursion(t.root)
print "ancestor",t.lowest_common_ancestor(t.root,110,125)