2. 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
42
31
3. Node:
A node having some data, references to its left and right
child nodes.
struct nodes
{
int data;
struct node *leftChild;
struct node *rightChild;
};
5. 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.
6. 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);
}
7. 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. 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))
11. 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))
13. 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)