#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;
}
}
我的程序停止运行。我想打印不同的树遍历。请解释我上面的代码中的错误。程序在两者之间运行并在某些地方停止。我正在尝试执行switch案例中的语句但它停止了。请建议一个解决方案。
答案 0 :(得分:1)
为节点线路分配内存时
LIST temp=(LIST)malloc(sizeof(LIST *));
您只分配指针LIST *
的大小。将该行替换为:
LIST temp=(LIST)malloc(sizeof(struct node));