-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathbinary_tree_part_2.py
103 lines (81 loc) · 2.88 KB
/
binary_tree_part_2.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
class BinarySearchTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def add_child(self, data):
if data == self.data:
return # node already exist
if data < self.data:
if self.left:
self.left.add_child(data)
else:
self.left = BinarySearchTreeNode(data)
else:
if self.right:
self.right.add_child(data)
else:
self.right = BinarySearchTreeNode(data)
def search(self, val):
if self.data == val:
return True
if val < self.data:
if self.left:
return self.left.search(val)
else:
return False
if val > self.data:
if self.right:
return self.right.search(val)
else:
return False
def in_order_traversal(self):
elements = []
if self.left:
elements += self.left.in_order_traversal()
elements.append(self.data)
if self.right:
elements += self.right.in_order_traversal()
return elements
def delete(self, val):
if val < self.data:
if self.left:
self.left = self.left.delete(val)
elif val > self.data:
if self.right:
self.right = self.right.delete(val)
else:
if self.left is None and self.right is None:
return None
elif self.left is None:
return self.right
elif self.right is None:
return self.right
min_val = self.right.find_min()
self.data = min_val
self.right = self.right.delete(min_val)
return self
def find_max(self):
if self.right is None:
return self.data
return self.right.find_max()
def find_min(self):
if self.left is None:
return self.data
return self.left.find_min()
def build_tree(elements):
print("Building tree with these elements:",elements)
root = BinarySearchTreeNode(elements[0])
for i in range(1,len(elements)):
root.add_child(elements[i])
return root
if __name__ == '__main__':
numbers_tree = build_tree([17, 4, 1, 20, 9, 23, 18, 34])
numbers_tree.delete(20)
print("After deleting 20 ",numbers_tree.in_order_traversal()) # this should print [1, 4, 9, 17, 18, 23, 34]
numbers_tree = build_tree([17, 4, 1, 20, 9, 23, 18, 34])
numbers_tree.delete(9)
print("After deleting 9 ",numbers_tree.in_order_traversal()) # this should print [1, 4, 17, 18, 20, 23, 34]
numbers_tree = build_tree([17, 4, 1, 20, 9, 23, 18, 34])
numbers_tree.delete(17)
print("After deleting 17 ",numbers_tree.in_order_traversal()) # this should print [1, 4, 9, 18, 20, 23, 34]