BINARY SEARCH
TREE
DEFINITION:
 Binary search tree is node based binary tree data
structure.
Each node has a key and an associated value.
27
14
10 19
35
4231
Node:
A node having some data, references to its left and right
child nodes.
struct nodes
{
int data;
struct node *leftChild;
struct node *rightChild;
};
BASIC OPERATION:
Search
Insert
Pre-ordetraversal
In-order traversal
Postordertraversal
OPERATION ON BINARY SEARCH TREE:
Search − Searches an element in a tree.
Insert − Inserts an element in a tree.
Pre-order Traversal − Traverses a tree in a pre-order
manner.
In-order Traversal − Traverses a tree in an in-order
manner.
Post-order Traversal − Traverses a tree in a post-order
manner.
SEARCH:
Start searching from the root node. Then if the data is
less than the key value, search for the element in the left
subtree. search for the element in the rightsubtree.
EG:
search(ptnode root, int key)
{
if (!root) return NULL;
if (key == root->key) return root;
if (key < root->key)
return search(root->left,key);
return search(root->right,key);
}
INSERT:
A new key is always inserted at leaf. We start searching a
key from root till we hit a leaf node.
EG:
void insert(TreeNode<ItemType>*& tree, ItemType item)
{
if(tree == NULL)
{
tree = new TreeNode<ItemType>;
tree->right = NULL;
tree->left = NULL;
tree->info = item;
}
else if(item < tree->info)
Insert(tree->left, item);
else
Insert(tree->right, item);
}
9
7
5
4 6 8
10
10
10>7
10>9
INSERT AN ELEMENT IN THE LEAF
NODE
INORDER TRAVERSAL:
Visit the nodes in the left subtree, then visit the root of
the tree, then visit the nodes in the right subtree .
Inorder(tree)
If tree is not NULL
Inorder(Left(tree))
Visit Info(tree)
Inorder(Right(tree))
IN ORDER
10
‘J’
‘E’
‘A
’
‘H
’
‘T
’
‘M’
‘Y
’
tre
e
Visit left subtree first Visit right subtree last
Visit second
PREORDER:
Visit the root of the tree first, then visit the nodes in the
left subtree, then visit the nodes in the right subtree
Preorder(tree)
If tree is not NULL
Visit Info(tree)
Preorder(Left(tree))
Preorder(Right(tree))
PREORDER
12
‘J’
‘E’
‘A
’
‘H
’
‘T
’
‘M’
‘Y
’
tre
e
Visit left subtree second Visit right subtree last
Visit first
POST ORDER:
Visit the nodes in the left subtree first, then visit the
nodes in the right subtree, then visit the root of the tree
Postorder(tree)
If tree is not NULL
Postorder(Left(tree))
Postorder(Right(tree))
Visit Info(tree)
POST ORDER:
POST ORDER
14
‘J’
‘E’
‘A
’
‘H
’
‘T
’
‘M’
‘Y
’
tre
e
Visit left subtree first Visit right subtree second
THANK YOU

Binary search tree