C 如何获取非空二叉树并打印它?

C 如何获取非空二叉树并打印它?,c,data-structures,binary-tree,C,Data Structures,Binary Tree,我构建了三个文件,包括MainFunc.c、AllFun.h和OtheFunc.c 程序发生运行时错误,不打印任何内容。但是,我需要它输出一个树作为以前的顺序。 我想问题可能是我建了一棵空树,但我无法解决它 MainFunc.c #包括“AllFun.h” int main(int argc,char*argv[]) { int nums[MaxSize]={0}; printf(“输入根节点的值:”); 对于(int i=0;i数据=v; node->lchild=node->rchild=N

我构建了三个文件,包括MainFunc.c、AllFun.h和OtheFunc.c

程序发生运行时错误,不打印任何内容。但是,我需要它输出一个树作为以前的顺序。 我想问题可能是我建了一棵空树,但我无法解决它

MainFunc.c

#包括“AllFun.h”
int main(int argc,char*argv[])
{
int nums[MaxSize]={0};
printf(“输入根节点的值:”);
对于(int i=0;i
好好玩

#包含//空
#包括
#包括
#定义最大尺寸10
类型定义结构节点{
int数据;
结构节点*lchild,*rchild;
}三烯醇;
TreeNode*创建(int nums[],int n);
无效前序(树节点*根);
OtheFunc.c

#包括“AllFun.h”
树节点*新节点(int v){
TreeNode*节点=(TreeNode*)malloc(sizeof(TreeNode));
如果(节点){
节点->数据=v;
node->lchild=node->rchild=NULL;
返回节点;
}
}
空插入(TreeNode*root,int x)
{
if(root==NULL){
root=newNode(x);
返回;
}
如果(根->数据lchild,x);
}
否则{
插入(根->rchild,x);
}
}
树节点*创建(int nums[],int n)
{
TreeNode*root=NULL;//构建一个空的根节点
对于(int i=0;i数据);
预订单(根->lchild);
预订单(根->rchild);
}

必须将节点作为指针传递给指针,然后函数可以更改指针:

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);
    }
}
void插入(TreeNode**root,int x)
{
如果(*root==NULL){
*root=newNode(x);
返回;
}
如果((*根)->数据lchild,x);
}
否则{
插入(&(*根)->rchild,x);
}
}
调用
insert(&root,nums[i])


root=newNode(x)insert
函数中的code>不会更改调用者函数中的变量,只会更改本地函数中的副本。
'newNode':并非所有控制路径都返回值
您可能希望
malloc
永远不会返回
NULL
,但如果确实存在问题。@mch我该如何修改我的代码?我的两分钱,我建议在取消引用
root
参数之前添加输入检查(如
if(root==NULL){perror(“错误输入”);return;}
。检查输入是一个好习惯。
#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);
#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);
}
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);
    }
}