【发布时间】:2021-08-04 00:34:27
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
节点创建
此结构创建结构节点数据类型
struct node
{
int data;
struct node *left, *right;
} * newnode;
创建函数
create() - 它首先分配节点所需的内存。当用户输入数据时,它会递归地调用自己来创建它的子节点,并继续这个过程。当用户输入 -1 时,它会终止递归并从调用它的地方返回。
struct node *create()
{
int x;
newnode = (struct node *)malloc(sizeof(struct node));
newnode->left = 0;
newnode->right = 0;
printf("Enter data(-1 for no node)\n");
scanf("%d", &x);
if (x == -1)
return 0;
newnode->data = x;
printf("Enter left child of %d\n", x);
newnode->left = create();
printf("Enter right child of %d\n", x);
newnode->right = create();
return newnode;
}
预购
preorder(struct node *root) - 该函数以先序方式显示树的数据
void preorder(struct node *root)
{
if (root == 0)
return;
printf("%d\n", root->data);
preorder(root->left);
preorder(root->right);
}
顺序
inorder(struct node *root) - 该函数将树的数据按顺序显示
void inorder(struct node *root)
{
if (root == 0)
return;
inorder(root->left);
printf("%d\n", root->data);
inorder(root->right);
}
后购
Postorder(struct node *root) - 该函数以后序方式显示树的数据
void postorder(struct node *root)
{
if (root == 0)
return;
postorder(root->left);
postorder(root->right);
printf("%d\n", root->data);
}
主要功能
Main 函数要求用户创建一棵树,然后根据用户输入的选择遍历它。问题是preorder、inorder和postorder都没有给出需要的输出,执行后导致死循环。
void main()
{
struct node *root;
root = 0;
int choice = 3, opt = 1;
while (opt)
{
printf("Select\n 1-for creation\n 2-for preorder\n 3-for inorder\n 4-for postorder\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
root = create();
break;
case 2:
printf("Preorder is: ");
preorder(root);
break;
case 3:
printf("Inorder is: ");
inorder(root);
break;
case 4:
printf("Postorder is: ");
postorder(root);
break;
default:
printf("Invalid choice");
break;
}
printf("Wanna continue \n1-for yes\n0-for no\n");
scanf("%d", &opt);
}
}
【问题讨论】:
标签: binary-tree recursive-datastructures inorder preorder postorder