Binary Search Tree
Binary Search Tree
• The left subtree of a node contains only nodes with keys lesser than
the node’s key.
• The right subtree of a node contains only nodes with keys greater
than the node’s key.
• The left and right subtree each must also be a binary search tree.
• There must be no duplicate nodes.
Binary Search Tree:
1) Implementation: Binary Search Tree
Consider the Following Binary Search Tree:
This binary search tree can be implemented
by creating node structure as follows:
Creating a node
class Binarysearchtree:
def __init__(self,key):
self.key = key
self.lchild = None
self.rchild = None
root = Binarysearchtree(10)
print(root.key)
print(root.lchild)
print(root.rchild)
2. Operations:
• There are three major operations that can be performed in the linked
list.
i) Insertion
ii) Deletion
iii) Searching
iv) Min and Max value
i) Insertion
While inserting a node in a binary search tree, three conditions may
arise.
1.The Binary search tree can be empty. i.e. Root itself will be a value
None.
2.The Value to be inserted is less than the root.
3.The value to be inserted is greater than the root.
• To implement the first condition, we just make a new node and declare
it as root.
• To implement second and third condition, We follow the following
approach.
• From the properties of a binary search tree, we can see that each sub
tree is a binary search tree in itself. Thus we can consider each node as
a root of another binary tree.
• While inserting a new node, if the value of the new data is less than
the value of the current node, we will add it to the left child of the
binary search tree, otherwise, we will add it to the right child.
def insert(self, val): if val < self.val:
if not self.val: if self.left:
self.left.insert(val)
self.val = val return
return self.left = BSTNode(val)
return
2) Node to be deleted has only one child: Copy the child to the node
and delete the child
else:
if self.rchild:
self.rchild.search(data)
else:
print("Node is not present")
iv) Min and Max value
Approach for finding minimum element:
• Traverse the node from root to left recursively until left is NULL.
• The node whose left is NULL is the node with minimum value.