-3
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
typedef struct node* LIST;
LIST getnode(int dat)
{
LIST temp=(LIST)malloc(sizeof(LIST *));
temp->data=dat;
temp->left=NULL;
temp->right=NULL;
return temp;
}
void preorder(struct node *tree)
{
if(tree==NULL)
    return;
printf("%d",tree->data);
preorder(tree->left);
preorder(tree->right);

}
void inorder(LIST tree)
{
if(tree==NULL)
 return;
inorder(tree->left);
printf("%d",tree->data);
inorder(tree->right);
}
void postorder(LIST tree)
{
if(tree==NULL)
    return;
postorder(tree->left);
postorder(tree->right);
printf("%d",tree->data);
}
int main()
{
int ch;
LIST root=NULL;
root=getnode(2);
printf("hi");
root->left=getnode(3);
root->right=getnode(5);
root->right->left=getnode(4);
root->right->right=getnode(9);
printf("How would you like to traverse the tree??
\n1.Preorder\n2.Inorder\n3.Postorder\nENTER YOUR CHOICE\n");         
scanf("%d",&ch);
switch(ch)
{
case 1:
    preorder(root);
    break;
case 2:
    inorder(root);
    break;
case 3:
    postorder(root);
    break;
}
}

my program stops running in between.I want to print the different tree traversals. please explain me the error in the above code.program is running in between and halts at some places.I am trying to execute the statements within the switch case but it halts.Please suggest a solution.

1 Answers1

1

When you allocate memory for your node line line

LIST temp=(LIST)malloc(sizeof(LIST *));

you are allocating only for a size of pointer LIST *. Replace that line with:

LIST temp=(LIST)malloc(sizeof(struct node));
isido
  • 66
  • 4