lanqi
lanqi

Reputation: 85

How can I get a non-empty binary tree and print it?

I built three files, which includes MainFunc.c, AllFun.h, and OtheFunc.c.

The program happens runtime error, which print nothing. However, I need it output a tree as previous order. I guess the problem may be that I built an empty tree, but I can't solve it.

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

Upvotes: 2

Views: 111

Answers (1)

mch
mch

Reputation: 9804

You have to pass the node as a pointer to pointer, then the function can change the pointer:

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

Call with insert(&root, nums[i]);:

https://ideone.com/nV5q1g

Upvotes: 2

Related Questions