Binary Search Tree (BST) : Finding Leaves : C Code
The following C code prints all the leaves nodes of a Binary Search Tree. A leaf-node is a node which has not left or right child. The code first scans the root node and looks whether it has a left and right child or not. If the condition is satisfied, it is a leave node or else we recursively examine the left and right child.
#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
int key;
struct binaryTree *right, *left;
};
typedef struct binaryTree node;
void insert(node **tree, int val);
void printLeaves(node *root);
int main() {
node *root;
int i,val,search;
root = NULL;
while(1) {
printf("\n Enter the value (-1 to exit):");
scanf("%d",&val);
if( val == -1)
break;
insert(&root, val);
}
printLeaves(root);
printf("\n");
return 0;
}
void printLeaves(node *root) {
if (root->right == NULL && root->left == NULL) {
printf("\n Leaf Node: %d",root->key);
return;
}
if(root->right != NULL)
printLeaves(root->right);
if(root->left != NULL)
printLeaves(root->left);
}
void insert(node **tree, int val) {
if((*tree) == NULL) {
*tree = (node *)malloc(sizeof(node));
(*tree)->key = val;
(*tree)->right=(*tree)->left=NULL;
return;
}
if(val < (*tree)->key)
insert(&(*tree)->left, val);
else if(val > (*tree)->key)
insert(&(*tree)->right, val);
}
#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
int key;
struct binaryTree *right, *left;
};
typedef struct binaryTree node;
void insert(node **tree, int val);
void printLeaves(node *root);
int main() {
node *root;
int i,val,search;
root = NULL;
while(1) {
printf("\n Enter the value (-1 to exit):");
scanf("%d",&val);
if( val == -1)
break;
insert(&root, val);
}
printLeaves(root);
printf("\n");
return 0;
}
void printLeaves(node *root) {
if (root->right == NULL && root->left == NULL) {
printf("\n Leaf Node: %d",root->key);
return;
}
if(root->right != NULL)
printLeaves(root->right);
if(root->left != NULL)
printLeaves(root->left);
}
void insert(node **tree, int val) {
if((*tree) == NULL) {
*tree = (node *)malloc(sizeof(node));
(*tree)->key = val;
(*tree)->right=(*tree)->left=NULL;
return;
}
if(val < (*tree)->key)
insert(&(*tree)->left, val);
else if(val > (*tree)->key)
insert(&(*tree)->right, val);
}
No comments:
Post a Comment