Showing posts with label Binary Tree. Show all posts
Showing posts with label Binary Tree. Show all posts

Monday, September 3, 2012

delete node from binary search tree!!

One of the complex operation on binary search tree is deleting a node. Insertion is easy by calling recursive insertion. But deletion wont work with recursive. We need to handle different cases for deletinga node. Lets see all possible cases one by one in detail.

Finding the node to delete: First step for deleting a node is to find the node in the tree. If the node is not in the tree, no need of delete. So below is the code snippet for finding the node.

current = root;
while(current!=NULL)
{
 if(current->info == key)
 {
 found = 1;
 break;
 }
 else
 {
 prev = current;
 if(current->info >= key)
 current = current->left;
 else
 current = current->right;
 }
}
Here we are maintaining two pointers prev and current, so that we can have the link to maintain. After finding the node to delete, there are four possible cases. See one by one.

Case1: Current node has zero child's as shown in below image. current node is either left or right child of the prev node.

we can simply remove the current node for the scenario which shown in the image. the code snippet is given below.
if((current->left == NULL) && (current->right == NULL))
{
 if(prev->left == current)
 prev->left = NULL;
 else
 prev->right = NULL;
 free(current);
}


Case2: Current node has one child either left or right.
Case2-A: Current node with right child as shown in the below image. There are two possibilities as shown in the below image.

See the sample code snippet below
if(current->left == NULL && current->right != NULL)
{
 if(prev->left == current)
 prev->left = current->right;
 else
 prev->right = current->right;
 free (current);
}

Case2-B: Current node with left child as shown in the below image. There are two possibilities as shown in the below image.
See the sample code snippet below.
if(current->right == NULL && current->left!=NULL)
{
 if(prev->left = current)
 prev->left = current->left;
 else
 prev->right = current->left;
 free(current);
}

Case 3: Current node with two child's as shown in the below image. There are again four possibilities as shown in the below images. These four cases we need to handle carefully.
Case3-A: If the current node right child has no children. The scenario is shown below.

We need to copy the tmp node data to current node and delete the tmp node.
Case3-B: If the current node has left child. This is the tricky one. If the left child is available (we can ignore whether right child is available or not), we need to find the smallest element in the left side and replace it with current node and delete the smallest node. To find the smallest element, just find the left most node from the tmp node. This is to satisfy the binary search tree property.
The sample code snippet is given below.
Case3-C: If the current node has only right child. The scenario is as shown in the image.
We need to copy the tmp data to current node and delete the tmp node. the code snippet is given below.
if(current->left != NULL && current->right != NULL)
{
 struct bst *tmp = current->right;
 //case3-A
 if(tmp->left == NULL && tmp->right == NULL)
 {
 current->info = tmp->info;
 //current = tmp;
 free(tmp);
 current->right = NULL;
 }
 //case3-B
 else if(current->right->left != NULL)
 {
 struct bst *left_current = current->right;
 struct bst *left_current_prev = current->right->left;
 while(left_current->left != NULL)
 {
 left_current_prev = left_current;
 left_current = left_current->left;
 }
 current->info = left_current->info;
 free(left_current);
 left_current_prev->left = NULL;
 }
 //case3-C
 else
 {
 struct bst *temp;
 temp = current->right;
 current->info = temp->info;
 current->right = temp->right;
 free(temp);
 }
}
Click here for the complete Binary search tree C program.

Monday, August 27, 2012

AVL tree insertion!!!

Lets constrcut the AVL tree with numbers 51, 26, 11, 6, 8, 4, 31, 21, 9, 16. AVL tree is a balanced Binary search tree. So to construct AVL tree, we need to follow below steps
  • insert the new element in such a way that if the element is less than the current node go left and if the element is greater than go right.
  • Check for the balance at each node after insertion (diff between left subtree and right subtree should be atmost one)
we will see step by step after inserting each number into the tree from starting. The numbers are
51, 26, 11, 6, 8, 4, 31, 21, 9, 16.
  • In step1 the tree is empty , so 51 is the first node, in step2 26 is inserted as a left child to the root node 51 and the tree is balanced.
  • In step3 11 is added as a left child to the node 26, becaus of this root node 51 is un-balanced, as it is shown in the image as red circle. We need to do the left left rotation which is a single rotation.
  • After the rotation, tree is balanced as shown in step4.
  • in step5 we are inserting 6 into the tree and which is as a left child to the node value 11.
  • in step6 we are inserting 8 into the tree and which is as a right child to the node value 6, because of this tree is un-balanced at node value 11 which is marked as red circle in the image.
  • for balancing the node we need to do right-left rotation which is a double rotation.
  • After the rotation, the tree is balanced and it is like as shown in step7.

  • In step8 we are inserting 4 into the tree and which is as a left child to node value 6. Becaus of this insertion, the tree is un-balanced at node value 26, and we need to do the left-left rotation as we did it earlier.
  • After the rotation the tree is like shown in step9. After that we need to insert 31 into the tree and which is as a left child to the node value 51 as shown in step10. And the tree is balanced.
  • In step11 we are inserted 21 into the tree whihc is as a right child to the node value 11. In step12 we inserted 9 as a left child to the node value 11. And the tree is balanced.
  • in step13, becaus of inserting 16 as a left child to the node value 21, the tree is un-balanced at node value 8.
  • We need to do the left right rotation which is a double rotation. And the resultant tree is as shown in step14.

Friday, August 24, 2012

AVL tree double rotation!!

Double rotation: need to do two rotations (left-right or right-left) to balance the tree. In this there are two types of sub rotations
    • Right Left rotation
    • Left Right rotation


Before Rotation
 Right-Left rotation: This is double rotation method in which we need to do two rotatios left and right. And this method needs to apply if the tree is as shown in the below image.
  • Here r3 is un balanced and we need to do RL rotation because r2 is right child of r1 and r1 is left child of un balanced r3.
  • 
  • Rotation is done in such a way that T1<r1<T2<r2<T3<r3<T4 property should satisfy after rotation.
  • After Rotation
  • To balance the tree, make r2 as root node and follow the binary search tree property for all other nodes.
  • Sample C code for Right Left rotation is given below. 
     
     //below steps are making the tree as shown in the image before rotation
     r1 = r3-<left;
     r2 = r1-<right;
     t2 = r2-<left;
     t3 = r2-<right;
     // actaul rotatiosn happens here
     r1-<right = t2;
     r3-<left = t3;
     r2-<left = r1;
     r2-<right = r3;
     //updte the new heihts for r1, r2, r3
     set_height(r1);
     set_height(r2);
     set_height(r3);
     *r = r2;
    
Left Right rotation: This is double rotation method in which we need to do two rotatios right and left. And this method needs to apply if the tree is as shown in the below image.
    
    Before Rotation
    
  • Here r1 is un balanced and we need to do RL rotation because r2 is left child of r3 and r3 is right child of un balanced r1.
  • Rotation is done in such a way that T1<r1<T2<r2<T3<r3<T4 property should satisfy after rotation.
  • After Rotation
  • To balance the tree, make r2 as root node and follow the binary search tree property for all other nodes.
  • Sample C code for Right Left rotation is given below.
     //below steps are making the tree as shown in the image before rotation
     r3 = r1-<right;
     r2 = r3-<left;
     t2 = r2-<left;
     t3 = r2-<right;
     // actaul rotatiosn happens here
     r1-<right = t2;
     r3-<left = t3;
     r2-<left = r1;
     r2-<right = r3;
     //updte the new heihts for r1, r2, r3
     set_height(r1);
     set_height(r2);
     set_height(r3);
     *r = r2;
    

AVL tree Single rotation!!

Single rotation: As the name says need to do one rotation (left or right) to balance the tree. In this there are two types of sub rotations
    • Left left rotation
    • Right right rotation
Left Left rotation: This is single rotation method which needs only one rotation. Left-Left rotation is required if the un-balanced tree is like as shown in the image.

    Before Rotation
  • Here r2 is un-balanced, because of adding the new node at T1 sub tree. Newly added node could either left or right. But it changes the balance property of r2.
  • To balance the tree, we need to do left-left rotation. This is because of newly added node is left child of r1 and r1 is a left child of un-balanced node r2.
  • Rotation is done in such a way that T1<r1<T2<r2<T3 property should satisfy after the rotation also.
  • After Rotation
    After the rotation the tree would be as shown in the image.
  • To make the tree balance, make the r2 as the root, and follow the Binary search tree property after that, we will get the resulted tree.
  • Sample code to do left-left rotation
    r1 = r2->left;
    //we are @r2, below statements are to make the tree like
    // shown in the image. so that rotation becomes easy
    t1 = r1->left;
    t2 = r1->right;
    t3 = r2->right;
    //actual rotation happens here
    r1->right = r2;
    r2->left = t2;
    // update the r1 , r2 height
    set_height(r1);
    set_height(r2);
    

Right Right rotation: This is single rotation method which needs only one rotation. Right-Right rotation is required if the un-balanced tree is like as shown in the image.

    
    Before Rotation
    
  • Here r1 is un-balanced, because of adding new node to the subtree T3 either left or right. But it changes the balanced property of r1.
  • We need to do right-right rotation because newly addded node is right side of r2, and r2 is right side of the unbalanced node r1.
  • Rotation is done in such a way that T1<r1<T2<r2<T3 property should satisfy after the rotation also.
  • After Rotation
  • After the rotation, resulted tree shouls be as shown in the image.
  • To make the tree balance, make the r2 as the root, and follow the Binary search tree property after that, we will get the resulted tree.
  • See the sample code for right-right rotation below.
     
     //we are @r1 and below statements are
     // used to arrange the pointers looks like in the image
     r2 = r1-<right;
     t1 = r1-<left;
     t2 = r2-<left;
     t3 = r2-<right;
     // actual rotations happens here
     r1-<right = t2;
     r2-<left = r1;
     set_height(r1);
     set_height(r2);
     *r = r2;
    





Thursday, August 23, 2012

AVL tree rotation!!!

AVL tree is balanced binary search tree. When we try to add new node to the AVL tree, it may become un-balanced. Generally the node which is unbalanced is grand parent of the newly inserted node. To balance the AVL tree, we need to do rotations. There are two types of rotations.

Monday, July 16, 2012

AVL Tree C program!!!

Below is C program for AVL Tree implementation.
#include<stdio.h>
#include<malloc.h>
typedef struct bst
{
 int info;
 int height;
 struct bst *left;
 struct bst *right;
}NODE;
typedef NODE* ROOT;
/*********************************
for setting/updating the height of the tree at each node
*************************************/
int set_height(ROOT r)
{
 int left_h = -1;
 int right_h = -1;
 if(r->left)
 left_h = r->left->height;
 if(r->right)
 right_h = r->right->height;
 if(left_h >= right_h)
 r->height = left_h+1;
 else
 r->height = right_h+1;
 return r->height;
}
/*********************************
return -1 if data1 is less than data2 
return 1 if data1 is greater than data2 
returns zero on equal
*************************************/
int compare(int data1, int data2)
{
 if(data1<data2)
 return -1;
 if(data1>data2)
 return 1;
 else
 return 0;
}
/*******************************
Doing Left-Left rotation
*******************************/
void rotate_LL(ROOT *r)
{
 NODE *r1, *r2 = *r,*t1,*t2,*t3;
 r1 = r2->left;
 t1 = r1->left;
 t2 = r1->right;
 t3 = r2->right;
 //actual rotation happens here
 r1->right = r2;
 r2->left = t2;
 // update the r1 , r2 height
 set_height(r1);
 set_height(r2);
 *r = r1;
}
/*******************************
Doing Right-Left rotation
*******************************/
void rotate_RL(ROOT *r)
{
 NODE *r1,*r2, *r3=*r,*t1,*t2,*t3,*t4;
 r1 = r3->left;
 r2 = r1->right;
 t2 = r2->left;
 t3 = r2->right;
 // actaul rotatiosn happens here
 r1->right = t2;
 r3->left = t3;
 r2->left = r1;
 r2->right = r3;
 //updte the new heihts for r1, r2, r3
 set_height(r1);
 set_height(r2);
 set_height(r3);
 *r = r2; 
}
/*******************************
Doing Left-Right rotation
*******************************/
void rotate_LR(ROOT *r)
{
 NODE *r1=*r, *r2,*r3,*t1,*t2,*t3,*t4;
 r3 = r1->right;
 r2 = r3->left;
 t2 = r2->left;
 t3 = r2->right;
 // actaul rotatiosn happens here
 r1->right = t2;
 r3->left = t3;
 r2->left = r1;
 r2->right = r3;
 //updte the new heihts for r1, r2, r3
 set_height(r1);
 set_height(r2);
 set_height(r3);
 *r = r2;
}
/*******************************
Doing Right-Right rotation
*******************************/
void rotate_RR(ROOT *r)
{
 NODE *r1=*r,*r2,*t1,*t2,*t3;
 r2 = r1->right;
 t1 = r1->left;
 t2 = r2->left;
 t3 = r2->right;
 // actaul rotatiosn happens here
 r1->right = t2;
 r2->left = r1;
 set_height(r1);
 set_height(r2);
 
 *r = r2;
}
/********************************************
It will returns rotation type.
1. Left-Left (LL)
2. Right-Left(RL)
3. Left-Right(RL)
4. Right-Right(RR)
********************************************/
int find_rotation_type(int parent_data, int child_data, int data)
{
 if(compare(data, parent_data)<0) // inserting left
 {
 if(compare(data, child_data)<0)
 return 1;
 else if(compare(data, child_data)==0)
 return 0;
 else 
 return 2;
 }
 else //inserting right
 {
 if(compare(data, child_data)>0)
 return 4;
 else if(compare(data, child_data)==0)
 return 0;
 else 
 return 3;
 }
}
/********************************************
Calling the corresponding AVL-rotation method
********************************************/
void do_rotation(ROOT *r, int rotation_type)
{
 if(rotation_type == 1)
 rotate_LL(r);
 else if(rotation_type == 2)
 rotate_RL(r);
 else if(rotation_type == 3)
 rotate_LR(r);
 else if(rotation_type == 4)
 rotate_RR(r);
 else
 printf("invalid rotation type \n");
}
/************************************************************
Try to insert the elements 50,25,10,5,7,3,30,20,8,15.
This order will cover all four rotations
************************************************************/
int insert(ROOT *r, int data)
{
 NODE *new_node, *root = *r;
 int left_h = -1, right_h = -1;
 int diff,rotation_type;
 //tree is empty
 if(root == NULL)
 {
 new_node = (NODE *)malloc(sizeof(NODE));
 new_node->info = data;
 new_node->height = 0;
 new_node->left = new_node->right = NULL;
 *r = new_node;
 return 0;
 }
 if(root->left)
 left_h = root->left->height;
 if(root->right)
 right_h = root->right->height;
 if(compare(data, root->info)<0)
 {
 left_h = insert(&(root->left), data);
 rotation_type = find_rotation_type(root->info, root->left->info, data);
 }
 else if(compare(data, root->info)>0)
 {
 right_h = insert(&(root->right), data);
 rotation_type = find_rotation_type(root->info, root->right->info, data);
 }
 else
 {
 printf("Duplicate key!!\n");
 return -1;
 }
 diff = left_h-right_h;
 if(diff>1 || diff<-1)
 {
 printf("Tree is Un-Balanced at node data %d ", root->info);
 if(rotation_type == 1)
 printf("need to do LL rotation\n");
 if(rotation_type == 2)
 printf("need to do RL rotation\n");
 if(rotation_type == 3)
 printf("need to do LR rotation\n");
 if(rotation_type == 4)
 printf("need to do RR rotation\n");
 //this call is for doing rotation
 do_rotation(r,rotation_type);
 printf("rotation done successfully\n");
 root = *r;
 }
 //set the height for the node and return the height
 return set_height(root);
}
/**************************************
Printing In-Order traversal of AVL Tree
**************************************/
void print_inorder(NODE *root)
{
 NODE *temp = root;
 if(temp)
 {
 print_inorder(temp->left);
 printf("%d ",temp->info);
 print_inorder(temp->right);
 }
}
/**************************************
Printing Pre-Order traversal of AVL Tree
**************************************/
void print_preorder(NODE *root)
{
 NODE *temp = root;
 if(temp)
 {
 printf("%d ",temp->info);
 print_preorder(temp->left);
 print_preorder(temp->right);
 }
}
/**************************************
Printing Post-Order traversal of AVL Tree
**************************************/
void print_postorder(NODE *root)
{
 NODE *temp = root;
 if(temp)
 {
 print_postorder(temp->left);
 print_postorder(temp->right);
 printf("%d ",temp->info);
 }
}
int main()
{
 ROOT r = NULL;
 int i,num,data,choice;
 printf("enter the no. of elements\n");
 scanf("%d",&num);
 printf("Enter the elements\n");
 for(i=0;i<num;i++)
 {
 scanf("%d",&data);
 insert(&r,data);
 }
 printf("1. Insert\n2. In-order\n3. Pre-order\n4. Post-order\n5. Height of the tree\n other input for exit\n");
 printf("Enter the choice\n");
 scanf("%d",&choice);
 while(1)
 {
 switch(choice)
 {
 case 1:
 printf("Enter the element\n");
 scanf("%d",&data);
 insert(&r,data);
 break;
 case 2:
 printf("Inorder is \n ");
 print_inorder(r);
 printf("\n");
 break;
 case 3:
 printf("\nPreorder is \n ");
 print_preorder(r);
 printf("\n");
 break;
 case 4:
 printf("\nPostorder is \n ");
 print_postorder(r);
 printf("\n");
 break;
 case 5:
 //height of the root node height is heoght of the tree 
 printf("\nHeight of the tree is %d\n",r->height);
 break;
 default:
 return 0;
 break;
 }
 printf("1. Insert\n2. In-order\n3. Pre-order\n4. Post-order\n5. Height of the tree\n other input for exit\n");
 printf("Enter the choice\n");
 scanf("%d",&choice);
 }
}

Friday, July 13, 2012

AVL trees!!!

AVL (Adelson-Velskii and Landis scientists who found this tree) trees are balanced Binary search trees. All the operations like addition, deletion and searching in the worst case of O(log(n)).

What are AVL Trees: AVL trees are balanced binary search trees. A tree said to be balanced if the height of the left sub tree and right sub tree difference should be at most one at each node. i.e left sub tree and right sub tree difference should either 0, 1, -1.

Why AVL Trees: The problem with Binary Search Tree (BST) is that, if the given input values are in any sorted order(ascending or descending) the BST will be completely left or right as shown below. So Search will take worst case of O(n) where n is the no. of nodes in the BST.

Left skewed BST

Right skewed BST












From the above images it is very clear that , BST is not advisable to construct for sorted input values.

How to construct AVL Tree: Construction of AVL tree is same as Binary search tree, but the difference is after inserting the new node into the tree or deleting a node from the tree, again need to check each node for the balance. if the tree is not balanced, we need to re-structure or rebuild the tree for balancing using rotation.

Algorithm for AVL Tree:
Step1: Get the element to insert into the tree.
Step2: if the tree is empty, make the node as root node.
Step3: If the tree is not empty, traverse the tree until it reaches NULL in such a way that
if(element > node->element)
move node to node->right
else if(element &lt; node->element)
move node to node->left

Step4: After inserting check for the height of the node in Tree
Step5: If any node is not balanced, find the rotation type.
Step6: After doing the rotation, adjust the new heights of the rotated nodes

Example of the AVL Tree: Below is the AVL tree which satisfies Binary search tree property at each node and the difference between left sub tree height and right sub tree height is at most 1.

AVL Tree
Here is C Program for AVL trees.

Wednesday, June 27, 2012

Construct binary tree from inorder and preorder

Here we will learn how to construct a binary tree from a given traversals Inorder and Preorder/Postorder. Traversal means visiting each node in the tree in some specified order like preorder, postorder or inorder. We will get the traversal from the given binary tree. And we can also construct binary tree from the given traversals. We see how to construct the tree from traversals.

Construct Binary Tree from Traversals: To construct binary tree we need
  • Inorder traversal data and
  • Postorder or Preorder traversal data
Lets construct bianry tree withe example:

Inorder: DBEAFCG
PreOrder: ABDECFG

As mentioned above, to construct a tree we need at least two traversals in that one must be Inorder and another must be either Preorder or Postorder. Inorder is for finding left and right child nodes and pre or post order is for finding the root node.
If the preorder is given, first element in the preoder is root node. And if the postorder is given last element is the root node. After finding the root node, go to Inorder and find the root node in the inorder and left elements of the root node are left childs and right elements of the root node are right childs. Repeat this process for all elements.

Step1: From Preorder first eleement is the root node.So here it is 'A'. If you see 'A' in in order and left of the A are left childs here DBE and right childs of A are FCG.

Step1 tree
PreOrder: ABDECFG
Inorder: DBE A FCG


Step 2: we will repeat the step1 for two sub elements BDE and CFG. from preorder first element is root node, here B and C are root nodes and from the Inorder D is the left child and E is the right child for B. Similarly F is the left child and G is the right child for C.

PreOrder: A BDE CFG

Step2 Tree
Inorder: DBE A FCG












Lets take another example with Inorder and Postorder.

Postorder: DHIEBJFGCA
Inorder: DBHEIAFJCG


Step1 Binary tree
Step1: From postorder last element is the root node, So here A is the root node and from from inorder we will find the left and right sub elements.

Postorder: DHIEB JFGC A
Inorder: DBHEI A FJCG

Step2 Binary Tree
Step2: we will repeat the step1 for left and right sub elements. From Inorder left elements are 5 and right elements are 4. we will split the Postorder like that and take the root nodes as B and C.

Postorder: DHIEB JFGC A
Inorder: D B HEI A FJ C G

Final Binary tree
Step3: For root node B left element is one(D) and right elements are three(HIE) and for C left element are two(JF) and right element is one(G).

Postorder: D HIE B JF G C A
Inorder: D B HEI A FJ C G

Tuesday, June 26, 2012

Binary Search Tree !!!

In computer science Binary search tree or BST is one of most common data structure used. A Binary search tree is a binary tree which follow the below properties
  • left sub tree of the node should contain less than or equal to node
  • right sub tree of the node should contain the greater than to the node
  • both left and right subtrees should also be a binary search tree
Binary search tree for the input values 8,13,3,11,1,6,14,12,4,7 is given below.
Binary Search Tree



One of the most advantage of Binary search tree is , sorting and searching operations are very efficient. Worst case complexity of searching using BST method is O(log(n)) where n is no. of nodes. And worst case for sorting using BST is O(n), Where as traditional sorting algorithms like bubble sort or quick sort the worst case is O(n*n). In the average case for the sorting in BST, the complexity reduces to (log(n)).

Operations on Binary Search Tree:
  • Searching
  • inserting
  • deleting
  • sort
  • traversal
Click here for complete working binary search tree C code.

Applications of the binary search tree:
  • Dictionaries
  • sets
  • multi sets
  • associate array

Monday, June 18, 2012

binary search tree C program !!

Below is the complete working C code with all operations in Binary Search Tree.
#include<stdio.h>
#include<malloc.h>
struct bst
{
 int info;
 struct bst *left;
 struct bst *right;
};
void delete(struct bst *root, int key);
struct bst *find_min(struct bst *node);
struct bst *find_max(struct bst *node);
struct bst *insert(struct bst *node, int key);
void print_postorder(struct bst *root);
void print_preorder(struct bst *root);
void print_inorder(struct bst *root);
int height(struct bst *root);
//deleting the element which handles three cases
//1. deleting node has no leaf nodes
//2. deleting node has one child(left or right)
//3. deleting node has two childs
void delete(struct bst *root, int key)
{
 struct bst *current;
 struct bst *prev;
 int found = 0;
 if(root == NULL)
 {
 printf("The BST is empty\n");
 return;
 }
 current = root;
 while(current!=NULL)
 {
 if(current->info == key)
 {
 found = 1;
 break;
 }
 else
 {
 prev = current;
 if(current->info >= key)
 current = current->left;
 else
 current = current->right;
 }
 }
 if(!found)
 {
 printf("given key element is not in the BST\n");
 return;
 }
 //leaf node , no left n right childs
 if((current->left == NULL) && (current->right == NULL))
 {
 if(prev->left == current)
 prev->left = NULL;
 else
 prev->right = NULL;
 free(current);
 }
 //single child node (either left or right child)
 if(current->left == NULL && current->right != NULL)
 {
 if(prev->left == current)
 prev->left = current->right;
 else
 prev->right = current->right;
 free (current);
 }
 if(current->right == NULL && current->left!=NULL)
 {
 if(prev->left = current)
 prev->left = current->left;
 else
 prev->right = current->left;
 free(current);
 }
 // need to handle the very complex case(node with both left n right childs)
 if(current->left != NULL && current->right != NULL)
 {
 struct bst *tmp = current->right;
 if(tmp->left == NULL && tmp->right == NULL)
 {
 current->info = tmp->info;
 free(tmp);
 current->right = NULL;
 }
 else if(current->right->left != NULL)
 {
 struct bst *left_current = current->right;
 struct bst *left_current_prev = current->right->left;
 while(left_current->left != NULL)
 {
 left_current_prev = left_current;
 left_current = left_current->left;
 }
 current->info = left_current->info;
 free(left_current);
 left_current_prev->left = NULL;
 }
 else
 {
 struct bst *temp;
 temp = current->right;
 current->info = temp->info;
 current->right = temp->right;
 free(temp);
 }
 }
}
//finding the min value
struct bst *find_min(struct bst *node)
{
 if(node == NULL)
 return NULL;
 if(node->left == NULL)
 return node;
 else
 return find_min(node->left);
}
//finding the max value
struct bst *find_max(struct bst *node)
{
 if(node!=NULL)
 {
 while(node->right!=NULL)
 node = node->right;
 }
 return node;
}
//adding the new element to the BST
struct bst *insert(struct bst *node, int key)
{
 if(node == NULL)
 {
 //creating the new node with the key and left n right sub nodes empty
 node = (struct bst *)malloc(sizeof(struct bst));
 node->info = key;
 node->left = node->right = NULL;
 }
 else if(node->info >= key)
 node->left = insert(node->left, key);
 else
 node->right= insert(node->right, key);
 return node;
}
//printing post order (LRP)
void print_postorder(struct bst *root)
{
 struct bst *temp = root;
 if(temp!=NULL)
 {
 print_postorder(temp->left);
 print_postorder(temp->right);
 printf("%d ",temp->info);
 }
}
//printing preorder(PLR)
void print_preorder(struct bst *root)
{
 struct bst *temp = root;
 if(temp!=NULL)
 {
 printf("%d ",temp->info);
 print_preorder(temp->left);
 print_preorder(temp->right);
 }
}
//printing inorder (LPR)
void print_inorder(struct bst *root)
{
 struct bst *temp = root;
 if(temp!=NULL)
 {
 print_inorder(temp->left);
 printf("%d ",temp->info);
 print_inorder(temp->right);
 }
}
// to find the height of the tree
int height(struct bst *root)
{
 struct bst *temp = root;
 int leftH = 0;
 int rightH = 0;
 if(temp == NULL)
 return 0;
 if(temp->left)
 leftH = height(temp->left);
 if(temp->right)
 rightH = height(temp->right);
 return leftH >rightH ? leftH+1 : rightH+1;
}
int main()
{
 struct bst *root=NULL;
 struct bst *tmp=NULL;
 int i,n,key,option;
 printf("Enter the no. elements in the BST\n");
 scanf("%n",&n);
 printf("Enter the list of elements in the BST\n");
 for(i=0;i<n;i++)
 {
 scanf("%d",&key);
 root = insert(root,key);
 }
 printf("Below are the possible opetaions you can performe in the above created BST\n");
 printf("1. Insert\n2. Delete\n3. In-Order\n4. Pre-Order\n5. Post-Order\n6. Find Minimum\n7. Find Max\n8. height\n other value for exit");
 scanf("%d,&option");
 while(1)
 {
 switch(option)
 {
 case 1:
 printf("Enter the valeu to insert into the BST\n");
 scanf("%d",&key);
 root = insert(root,key);
 break;
 case 2:
 printf("Enter the value to delete from the BST\n");
 scanf("%d",&key);
 delete(root,key);
 break;
 case 3:
 print_inorder(root);
 break;
 case 4:
 print_preorder(root);
 break;
 case 5:
 print_postorder(root);
 break;
 case 6:
 if(tmp)
 printf("Min value in BST is %d\n",tmp->info);
 break;
 case 7:
 tmp = find_max(root);
 if(tmp)
 printf("Max value in BST is %d\n",tmp->info);
 break;
 case 8:
 printf("height of the BST is %d\n",height(root));
 break;
 default:
 return 0;
 break;
 }
 printf("Below are the possible opetaions you can performe in the above created BST\n");
 printf("1. Insert\n2. Delete\n3. In-Order\n4. Pre-Order\n5. Post-Order\n6. Find Minimum\n7. Find Max\n8. height\n other value for exit");
 scanf("%d,&option");
 }
}

Friday, March 9, 2012

What is Threaded binary tree?

The Binary tree traversals mostly involves stack manipulations which will take lot of memory. If the stack memory is low, Binary trees could be problems. Here comes the Threaded binary trees. These cane be useful where stack memory is limited or where stack of the parent pointers are not available.

Properties of threade binary tree:
  • if the left sub tree is empty, left link points to the in-order predecessor
  • if the right sub tree is empty, right link points to the in-order successor.



Fig: Threaded binary tree
 In-order traversals for the above binary tree is DBHEIAFCJG. As per the threaded binary tree rules , links are connected in the above image. The basic difference between binary tree and threaded binary tree is that in binary tree childs are null if there is no child associated with it, so there is no way to traverse back. Where as in threaded binary tree child nodes are assosiated with in-order successor or predessosor if no child assosiated with it. So back traversals is easy in this. There are many ways to implement the threaded binary tree. Below is the simple node structure for this.
struct node
{
 int info;
 struct node *left;
 struct node *right;
 //two boolian variables are true for only child nodes to make thread links. 
 bool llink,rlink; 
};
Subscribe to: Posts (Atom)

Popular Posts

AltStyle によって変換されたページ (->オリジナル) /