-
Notifications
You must be signed in to change notification settings - Fork 307
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #46 from aman-mi/patch-1
add bst.py
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
# Python program to demonstrate insert operation in binary search tree | ||
|
||
# A utility class that represents an individual node in a BST | ||
class Node: | ||
def __init__(self,key): | ||
self.left = None | ||
self.right = None | ||
self.val = key | ||
|
||
# A utility function to insert a new node with the given key | ||
def insert(root,node): | ||
if root is None: | ||
root = node | ||
else: | ||
if root.val < node.val: | ||
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) | ||
|
||
# A utility function to do inorder tree traversal | ||
def inorder(root): | ||
if root: | ||
inorder(root.left) | ||
print(root.val) | ||
inorder(root.right) | ||
|
||
|
||
# Driver program to test the above functions | ||
# Let us create the following BST | ||
# 50 | ||
# / \ | ||
# 30 70 | ||
# / \ / \ | ||
# 20 40 60 80 | ||
r = Node(50) | ||
insert(r,Node(30)) | ||
insert(r,Node(20)) | ||
insert(r,Node(40)) | ||
insert(r,Node(70)) | ||
insert(r,Node(60)) | ||
insert(r,Node(80)) | ||
|
||
# Print inoder traversal of the BST | ||
inorder(r) | ||
|