-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search_tree.py
71 lines (57 loc) · 1.83 KB
/
binary_search_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
from structures.tree_node import BinaryTreeNode
class BinarySearchTree():
def __init__(self):
self.head = None
def insert(self, val):
if not self.head:
self.head = BinaryTreeNode(val, None)
return
def add_node_recursive(node):
if val < node.value:
if node.left:
add_node_recursive(node.left)
else:
node.left = BinaryTreeNode(val, node)
else:
if node.right:
add_node_recursive(node.right)
else:
node.right = BinaryTreeNode(val, node)
add_node_recursive(self.head)
def min(self):
return self.head.min().value
def delete(self, value):
self.head.delete(value)
def search(self, value):
node = self.head
while node:
if value == node.value:
return node
if value > node.value:
node = node.right
else:
node = node.left
# return None if not found
return node
def in_order_traversal(self):
output = []
def recur(node):
if node:
recur(node.left)
output.append(node.value)
recur(node.right)
recur(self.head)
return output
def merge(self, tree):
def mergeOntoT1(t1, t2):
if not t1:
return t2
if not t2:
return t1
t1.value += t2.value
# look left
t1.left = mergeOntoT1(t1.left, t2.left)
# look right
t1.right = mergeOntoT1(t1.right, t2.right)
return t1
mergeOntoT1(self.head, tree.head)