Repository navigation
Expand file tree
/
Copy pathBinary_search_tree.py
More file actions
63 lines (54 loc) · 1.65 KB
/
Copy pathBinary_search_tree.py
File metadata and controls
63 lines (54 loc) · 1.65 KB
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
# a program used to demonstrate simple operations in a binary search tree
class Node:
def __init__(self, node):
self.left = None
self.right = None
self.node = node
def insert(self, objnode):
if self.node:
if objnode < self.node:
if self.left is None:
self.left = Node(objnode)
else:
self.left.insert(objnode)
elif objnode > self.node:
if self.right is None:
self.right = Node(objnode)
else:
self.right.insert(objnode)
else:
self.node = objnode
def printBST(self):
if self.left:
self.left.printBST()
print(self.node)
if self.right:
self.right.printBST()
def Search(self, root, key):
while root != None:
# pass right subtree as new tree
if key > root.node:
root = root.right
# pass left subtree as new tree
elif key < root.node:
root = root.left
else:
return True # if the key is found return 1
return False
n = int(input("Enter your Root node"))
root = Node(n)
while 1:
a = int(input("enter the node you want to insert"))
root.insert(a)
ch = input("Do you want to continue Y or N")
if ch == "Y" or ch == "y":
continue
else:
break
print("Your final binary search tree is\n")
root.printBST()
x = int(input("Enter key to search for"))
if root.Search(root, x):
print("Yes key exists in the tree")
else:
print("Not found!")