Created
March 30, 2013 18:47
-
-
Save kunalkushwaha/5277894 to your computer and use it in GitHub Desktop.
Binary tree creation and in-order printing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
typedef struct _node | |
{ | |
int data; | |
struct _node *left; | |
struct _node *right; | |
}node; | |
node * add_node(node *node_ptr, int data) | |
{ | |
if(node_ptr) | |
{ | |
printf("Already memory allocated, possible memory leak\n"); | |
} | |
else | |
{ | |
node_ptr = (node *)malloc(sizeof(node)); | |
if(!node_ptr) | |
{ | |
printf("error\n"); | |
return NULL; | |
} | |
} | |
// printf("Adding new node \n"); | |
node_ptr->data = data; | |
node_ptr->left = node_ptr->right = NULL; | |
return node_ptr; | |
} | |
int add_node_bintree(node **root,int data) | |
{ | |
if(!*root) | |
{ //1st element in tree. | |
printf("Added node in head\n"); | |
*root=add_node(*root, data); | |
if(!root) | |
{ | |
printf("Error \n"); | |
} | |
} | |
else if(data < (*root)->data) | |
{ | |
printf("adding node to left\n"); | |
if(!(*root)->left) | |
{ | |
(*root)->left = add_node((*root)->left,data); | |
} | |
else | |
{ | |
add_node_bintree(&((*root)->left), data); | |
} | |
} | |
else | |
{ | |
printf("adding node to right\n"); | |
if(!(*root)->right) | |
{ | |
(*root)->right = add_node((*root)->right, data); | |
} | |
else | |
{ | |
add_node_bintree(&((*root)->right), data); | |
} | |
} | |
} | |
void print_bintree(node *root) | |
{ | |
if(!root) | |
return; | |
print_bintree(root->left); | |
printf(" %d -> ",root->data); | |
print_bintree(root->right); | |
} | |
int main() | |
{ | |
int array[10]={5,6,42,12,3,80,12,13,10,11}; | |
int i=0; | |
node *root = NULL; | |
for(i=0; i < 10; i++) | |
{ | |
printf("adding data to tree %d \n",array[i]); | |
add_node_bintree(&root,array[i]); | |
} | |
printf("Data in tree \n Printing data\n"); | |
print_bintree(root); | |
printf(" NULL \n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment