【问题标题】:How can I get a non-empty binary tree and print it?我怎样才能得到一个非空的二叉树并打印它?
【发布时间】: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


【解决方案1】:

你必须将节点作为指向指针的指针传递,然后函数可以改变指针:

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(&amp;root, nums[i]);:

https://ideone.com/nV5q1g

【讨论】:

  • 我的两分钱,我建议在取消引用root参数之前添加输入检查(如if (root==NULL) { perror("wrong input"); return; }。检查输入是一个好习惯。
猜你喜欢
  • 2019-11-04
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多