-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbst.py
87 lines (71 loc) · 2.14 KB
/
bst.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
def insert(root,node):
l1=[ord(c) for c in root.val]
l2=[ord(c) for c in node.val]
if root is None:
root = node
else:
if l1 < l2:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
def deletenode(root,k):
if root is None:
return root
if k < root.val:
root.left = deletenode(root.left,k)
if k > root.val:
root.right = deletenode(root.right,k)
def searchelement(root,k):
if root is None:
return root
if root.val < k:
root.right = searchelement(root.right,k)
if root.val > k:
root.left = searchelement(root.left,k)
root=raw_input("Enter Root Element:\t")
def main():
global key
r = Node(root)
while True:
print "-"*50
print "Binary Search Dictionary"
print "1.Insert Element"
print "2.Show Tree"
print "3.Delete Element"
print "4.Search Element"
print "5.Exit"
print "-"*50
ch=input("Enter Your Choice")
if ch==1:
val=raw_input("Enter Word to be inserted:\t")
insert(r,Node(val))
if ch==2:
print "Your Tree in INORDER :\n"
inorder(r)
if ch==3:
d = raw_input("Enter The Word to delete")
deletenode(r,Node(d) )
if ch==4:
l = raw_input("Enter The Element to search")
searchelement(r,Node(l))
if ch==5:
print ("Thank You")
break
if __name__=='__main__':
main()