Skip to content

Commit 416e725

Browse files
Added Binary Search Tree Python code
1 parent 9bccf15 commit 416e725

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

BinarySearchTree.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Node:
2+
3+
def __init__(self, data):
4+
5+
self.left = None
6+
self.right = None
7+
self.data = data
8+
9+
# Insert method to create nodes
10+
def insert(self, data):
11+
12+
if self.data:
13+
if data < self.data:
14+
if self.left is None:
15+
self.left = Node(data)
16+
else:
17+
self.left.insert(data)
18+
elif data > self.data:
19+
if self.right is None:
20+
self.right = Node(data)
21+
else:
22+
self.right.insert(data)
23+
else:
24+
self.data = data
25+
# findval method to compare the value with nodes
26+
def findval(self, lkpval):
27+
if lkpval < self.data:
28+
if self.left is None:
29+
return str(lkpval)+" Not Found"
30+
return self.left.findval(lkpval)
31+
elif lkpval > self.data:
32+
if self.right is None:
33+
return str(lkpval)+" Not Found"
34+
return self.right.findval(lkpval)
35+
else:
36+
print(str(self.data) + ' is found')
37+
# Print the tree
38+
def PrintTree(self):
39+
if self.left:
40+
self.left.PrintTree()
41+
print( self.data),
42+
if self.right:
43+
self.right.PrintTree()
44+
45+
46+
root = Node(12)
47+
root.insert(6)
48+
root.insert(14)
49+
root.insert(3)
50+
print(root.findval(7))
51+
print(root.findval(14))

0 commit comments

Comments
 (0)