Skip to content

Commit c58d0a1

Browse files
authored
Binary search tree
1 parent ccf4888 commit c58d0a1

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed

tree/binary-search-tree.py

+108
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
"""
2+
Binary Search Tree: Binary tree arranged according to binary search property.
3+
4+
Example:
5+
8
6+
/ \
7+
3 10
8+
/ \ \
9+
1 6 14
10+
/ \ /
11+
4 7 13
12+
Operations:
13+
1. Insertion
14+
2. Insertion of reverse sorted list
15+
3. Search
16+
4.is_bst_satisfied : check if tree is BST
17+
18+
"""
19+
class Node(object):
20+
def __init__(self,value):
21+
self.value = value
22+
self.left = None
23+
self.right = None
24+
25+
class BinarySearchTree(object):
26+
def __init__(self,root):
27+
self.root = Node(root)
28+
29+
def insert(self,new_val):
30+
self.insert_helper(self.root,new_val)
31+
32+
def insert_helper(self,current,value):
33+
if value <current.value:
34+
if current.left:
35+
self.insert_helper(current.left,value)
36+
else:
37+
current.left = Node(value)
38+
else:
39+
if current.right:
40+
self.insert_helper(current.right,value)
41+
else:
42+
current.right = Node(value)
43+
44+
return
45+
46+
47+
48+
def search(self,value):
49+
return self.search_helper(self.root,value)
50+
51+
def search_helper(self,current,value):
52+
if current:
53+
if current.value == value:
54+
return True
55+
elif value < current.value:
56+
return self.search_helper(current.left,value)
57+
58+
else:
59+
return self.search_helper(current.right,value)
60+
61+
return False
62+
63+
def is_bst_satisfied(self):
64+
def helper(node,lw=float('-inf'),mx=float('inf')):
65+
if not node:
66+
return True
67+
val = node.value
68+
69+
if val <= lw:
70+
return False
71+
if val> mx:
72+
return False
73+
74+
if not helper(node.left,lw,val):
75+
return False
76+
if not helper(node.right,val,mx):
77+
return False
78+
return True
79+
80+
81+
82+
return helper(self.root)
83+
84+
85+
86+
87+
88+
89+
90+
91+
bst = BinarySearchTree(8)
92+
bst.insert(3)
93+
bst.insert(10)
94+
bst.insert(1)
95+
bst.insert(6)
96+
97+
# print(bst.search(19))
98+
99+
bst = BinarySearchTree(10)
100+
bst.insert(3)
101+
bst.insert(1)
102+
bst.insert(25)
103+
bst.insert(9)
104+
bst.insert(13)
105+
106+
# print(bst.search(9))
107+
# print(bst.search(14))
108+
print(bst.is_bst_satisfied())

0 commit comments

Comments
 (0)