Ex 6-Tree
Ex 6-Tree
SEARCH:
Step 1: Compare the current node data with the key if:
If the key is found, then return the node.
If the key is lesser than the node data, move the current to the left node and again
repeat step 1.
If the key is greater then move to the right and repeat step 1.
Step 2: If the node is not found then return NULL.
Program
#include <stdio.h>
#include <stdlib.h>
struct treeNode {
int data;
struct treeNode *left, *right;
};
tmpNode = *node;
(*node)->right->left = (*node)->left;
(*parent)->left = (*node)->right;
free(tmpNode);
*node = (*parent)->left;
} else {
/*
* Deleting a node with two children.
* First, find the smallest node in
* the right subtree. Replace the
* smallest node with the node to be
* deleted. Then, do proper connections
* for the children of replaced node.
*/
tmpNode = (*node)->right;
while (tmpNode->left) {
tmpParent = tmpNode;
tmpNode = tmpNode->left;
}
tmpParent->left = tmpNode->right;
tmpNode->left = (*node)->left;
tmpNode->right =(*node)->right;
free(*node);
*node = tmpNode;
}
} else if (data < (*node)->data) {
/* traverse towards left subtree */
deletion(&(*node)->left, node, data);
} else if (data > (*node)->data) {
/* traversing towards right subtree */
deletion(&(*node)->right, node, data);
}
}
int main() {
int data, ch;
while (1) {
printf("1. Insertion in Binary Search Tree\n");
printf("2. Deletion in Binary Search Tree\n");
printf("3. Search Element in Binary Search Tree\n");
printf("4. Inorder traversal\n5. Exit\n");
printf("Enter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
while (1) {
printf("Enter your data:");
scanf("%d", &data);
insertion(&root, data);
printf("Continue Insertion(0/1):");
scanf("%d", &ch);
if (!ch)
break;
}
break;
case 2:
printf("Enter your data:");
scanf("%d", &data);
deletion(&root, NULL, data);
break;
case 3:
printf("Enter value for data:");
scanf("%d", &data);
findElement(root, data);
break;
case 4:
printf("Inorder Traversal:\n");
traverse(root);
printf("\n");
break;
case 5:
exit(0);
default:
printf("u've entered wrong option\n");
break;
}
}
return 0;
}
Output
Delete node 9
20
/ \
14 25
\ / \
19 21 30
\ /
23 26
Delete node 14
20
/ \
19 25
/ \
21 30
\ /
23 26
Delete node 30
20
/ \
19 25
/ \
21 26
\
23
Delete node 20
21
/ \
19 25
/ \
23 26
21
/ \
19 25
/ / \
15 23 26
/ \
14 16
\
17
21
/ \
19 25
/ / \
16 23 26
/ \
14 17
RESULT: Thus, the C program was implemented and perform the operations using of
Tree