【发布时间】:2021-05-12 08:57:07
【问题描述】:
我构建了三个文件,分别是 MainFunc.c、AllFun.h 和 OtheFunc.c。
程序发生运行时错误,不打印任何内容。但是,我需要它以先前的顺序输出一棵树。 我想问题可能是我建了一棵空树,但我解决不了。
MainFunc.c
#include "AllFun.h"
int main(int argc, char* argv[])
{
int nums[MaxSize] = { 0 };
printf("Enter value of root node: ");
for (int i = 0; i < MaxSize; ++i) {
scanf_s("%d", &nums[i]);
}
TreeNode* root = create(nums, MaxSize);
preorder(root);
return 0;
}
AllFun.h
#include <stddef.h> // NULL
#include <stdlib.h>
#include <stdio.h>
#define MaxSize 10
typedef struct node {
int data;
struct node* lchild, * rchild;
} TreeNode;
TreeNode *create(int nums[], int n);
void preorder(TreeNode *root);
OtheFunc.c
#include "AllFun.h"
TreeNode* newNode(int v) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
if (node) {
node->data = v;
node->lchild = node->rchild = NULL;
return node;
}
}
void insert(TreeNode* root, int x)
{
if (root == NULL) {
root = newNode(x);
return;
}
if (root->data < x) {
insert(root->lchild, x);
}
else {
insert(root->rchild, x);
}
}
TreeNode *create(int nums[], int n)
{
TreeNode* root = NULL; // Build a empty root node
for (int i = 0; i < n; i++) {
insert(root, nums[i]);
}
return root;
}
void preorder(TreeNode* root)
{
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorder(root->lchild);
preorder(root->rchild);
}
【问题讨论】:
-
insert函数中的root = newNode(x);不会改变调用函数中的变量,只改变本地函数中的副本。 -
'newNode': not all control paths return a value你可能认为malloc永远不会返回NULL,但如果它真的返回,你就有问题了。 -
@mch 我应该如何修改我的代码?
标签: c data-structures binary-tree