【问题标题】:program is running in between and halts at some places程序在两者之间运行并在某些地方停止
【发布时间】:2014-06-09 10:06:25
【问题描述】:
#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 case 中的语句,但它停止了。请提出解决方案。

【问题讨论】:

  • 请缩进您的代码。
  • 根据您的代码,一次运行只能打印一种类型的遍历。请给出一个位置,你停在哪里?

标签: c tree-traversal


【解决方案1】:

当你为你的节点线线分配内存时

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

您只分配指针LIST * 的大小。将该行替换为:

LIST temp=(LIST)malloc(sizeof(struct node));

【讨论】:

    猜你喜欢
    • 2021-01-10
    • 2021-10-24
    • 1970-01-01
    • 2021-06-04
    • 2019-06-30
    • 1970-01-01
    • 2022-11-19
    • 2013-02-24
    • 2012-09-09
    相关资源
    最近更新 更多