Skip to content

Instantly share code, notes, and snippets.

@haridutt12
Last active July 12, 2016 04:34
Show Gist options
  • Save haridutt12/31a5d0b6569421c53405d04e4b25011b to your computer and use it in GitHub Desktop.
Save haridutt12/31a5d0b6569421c53405d04e4b25011b to your computer and use it in GitHub Desktop.
code for binary tree creation and traversal(preorder)
#include<stdio.h>
#include<malloc.h>
struct bt
{
int data;
struct bt *left;
struct bt *right;
};
struct bt* create(struct bt *h)
{
struct bt *p,*q;
int side,y=1;
h=(struct bt *)malloc(sizeof(struct bt));
scanf("%d",&h->data);
h->left=NULL;
h->right=NULL;
while(y) {
p=h;
struct bt *t=(struct bt *)malloc(sizeof(struct bt));
printf("enter value to be added ");
scanf("%d",&t->data);
t->left=NULL;
t->right=NULL;
while(p!=NULL){
q=p;
printf("enter side");
scanf("%d",&side);
if(side==1){
p=p->left;
}
else{
p=p->right;
}
}
if(side==1){
q->left=t;
}
else{
q->right=t;
}
printf("1 to cont: ");
scanf("%d",&y);
}
return h;
}
void pre(struct bt *h)
{
while(h!=NULL){
printf("%d",h->data);
pre(h->left);
pre(h->right);
}
}
void main()
{
struct bt *head;
head=create(head);
pre(head);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment