Professional Documents
Culture Documents
Tree Data Structure Slides
Tree Data Structure Slides
Tree Data Structure Slides
Post-Ordered Traversal:
a) Traverse the lefts of sub-tree
b) Traverse the rights of sub-tree
c) Visit the root node
Binary Search Tree (BST)
Binary Search Tree:
A binary tree in which the left child node of a tree or sub-tree has lesser value than its
root node but the right child node has greater value than its root node, such a binary tree is
called Binary Search Tree or BST.
When a BST is traversed in-order and the data item of each node is printed/read, then the data
item is printed in ascending order.
Advantages of BST:
Easy to perform operations i.e. insertion, creating new tree, searching and deletion in BST
Example:
Construction of BST for the given values, such as
45 30 35 25 60 70 80 55
4 3 30 25 16 10 8 5
Structure for Node Creation
struct node
{
int data;
struct node *leftChild;
struct node *rightChild;
};
BST Basic Operations
• The basic operations that can be performed on a binary search tree
data structure, are the following −
• Insert ()− Inserts an element in a tree/create a tree.
• Search () − Searches an element in a tree.
• Delete () – Delete 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.
Algorithm for insertion in BST
If root is NULL
then create root node
Return
If data found
return node
Endwhile
return data not found
end if
Searching in BST
struct node* search(int data) {
struct node *current = root;
printf("Visiting elements: ");
while(current->data != data) {
if(current != NULL)
printf("%d ",current->data);
//go to left tree
if(current->data > data) {
current = current->leftChild;
}
//else go to right tree
else {
current = current->rightChild;
}
//not found
if(current == NULL) {
return NULL;
}
return current;
}
}
Deletion in BST
Deletion of left most node (Minimum Data Item)
s = root;
while(s -> left != NULL)
{
par=s;
s=s->left;
}
par->left=s->right;
delete s;
Deletion in BST
Deletion of Right most node (Maximum Data Item)
s = root;
while(s -> right != NULL)
{
par=s;
s=s->right;
}
par->right=s->right;
delete s;
Binary Search Tree Deletion Cases