Binary Search Tree
Binary Search Tree
A Binary tree T is a Binary Search Tree (BST), if each node N of T has the following
property : The value at N is greater than every value in the left subtree of N and is less
than every value in the right subtree of N.
A Binary Search Tree (BST) is a special type of binary tree in which the left child of a
node has a value less than the node’s value and the right child has a value greater than
the node’s value. This property is called the BST property and it makes it possible to
efficiently search, insert, and delete elements in the tree.
BST are used to maintain a dynamically changing dataset in sorted order, which
allows for quick lookup, addition, and removal of items.
Binary Tree: Each node has at most two children, commonly referred to as
the left child and the right child.
Ordered Structure: For every node N, the values of all the nodes in the left
subtree of N are less than the value of N, and the values of all the nodes in
the right subtree of N are greater than the value of N. This is known as the
binary search property.
No Duplicate Nodes: Typically, BSTs do not contain duplicate values. Each
node has a distinct key or value.
If root is NULL:
root = CreateNode(value)
return root
If root.left is NULL:
root.left = CreateNode(value)
Else:
Insert(root.left, value)
If root.right is NULL:
root.right = CreateNode(value)
Else:
Insert(root.right, value)
return root
return root
Else:
1. Find the Node: Use the search operation to find the node to be deleted.
2. Case 1 - Leaf Node: If the node is a leaf (no children), simply remove it.
3. Case 2 - One Child: If the node has only one child, remove the node and
replace it with its child.
4. Case 3 - Two Children:
o Find the node's in-order successor (the smallest node in its right
subtree) or in-order predecessor (the largest node in its left subtree).
o Replace the node's value with the in-order successor/predecessor's
value.
o Delete the in-order successor/predecessor (which will be a simpler
case, as it has at most one child).
Algorithm
Function Delete(root, value):
If root is NULL:
return root
Else:
If root.left is NULL:
temp = root.right
Free(root)
return temp
temp = root.left
Free(root)
return temp
temp = MinValueNode(root.right)
root.value = temp.value
return root
Function MinValueNode(node):
current = node
current = current.left
return current