Skip to content

Commit 60cd818

Browse files
authored
Merge pull request #175 from pratik0527/patch-6
Inorder_BST.py
2 parents 36530b9 + b497f19 commit 60cd818

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Python program to demonstrate insert operation in binary search tree
2+
3+
# A utility class that represents an individual node in a BST
4+
class Node:
5+
def __init__(self,key):
6+
self.left = None
7+
self.right = None
8+
self.val = key
9+
10+
# A utility function to insert a new node with the given key
11+
def insert(root,node):
12+
if root is None:
13+
root = node
14+
else:
15+
if root.val < node.val:
16+
if root.right is None:
17+
root.right = node
18+
else:
19+
insert(root.right, node)
20+
else:
21+
if root.left is None:
22+
root.left = node
23+
else:
24+
insert(root.left, node)
25+
26+
# A utility function to do inorder tree traversal
27+
def inorder(root):
28+
if root:
29+
inorder(root.left)
30+
print(root.val)
31+
inorder(root.right)
32+
33+
34+
# Driver program to test the above functions
35+
# Let us create the following BST
36+
# 50
37+
# / \
38+
# 30 70
39+
# / \ / \
40+
# 20 40 60 80
41+
r = Node(50)
42+
insert(r,Node(30))
43+
insert(r,Node(20))
44+
insert(r,Node(40))
45+
insert(r,Node(70))
46+
insert(r,Node(60))
47+
insert(r,Node(80))
48+
49+
# Print inoder traversal of the BST
50+
inorder(r)

0 commit comments

Comments
 (0)