-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-search-tree.py
46 lines (36 loc) · 1.06 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
# Binary search tree
# O(log(n)) for average case
# O(n) for worst case
class Node():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(toBeInsertedNode,currentNode):
if(toBeInsertedNode.data>currentNode.data):
if(currentNode.right is None):
currentNode.right = toBeInsertedNode
return
else:
insert(toBeInsertedNode,currentNode.right)
if(toBeInsertedNode.data<currentNode.data):
if(currentNode.left is None):
currentNode.left = toBeInsertedNode
return
else:
insert(toBeInsertedNode,currentNode.left)
def bst(array):
root = Node(array[0])
for i in range(1,len(array)):
toBeInsertedNode = Node(array[i])
insert(toBeInsertedNode,root)
return root
def printTreeSorted(node):
if node is None:
return
printTreeSorted(node.left)
print(node.data, end = " ")
printTreeSorted(node.right)
pre = [10, 5, 1, 7, 40, 50]
ss = bst(pre)
printTreeSorted(ss)