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

问题描述

我构建了三个文件包括 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);
}

解决方法

必须将节点作为指针传递给指针,然后函数才能改变指针:

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);
    }
}

insert(&root,nums[i]);通话:

https://ideone.com/nV5q1g