打印二叉树

时间:2019-03-09 18:01:15

标签: c binary-tree

我有2个创建树的功能

struct tree *createNewNode(int data){
    struct tree *newNode = malloc(sizeof(struct tree));
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

struct tree *insert(struct tree *root, int data){
    if(root == NULL) root = createNewNode(data);
    else if(data < root->data) root->left = insert(root->left, data);
    else root->right = insert(root->right, data);
    return root;
}

和打印树的功能

void inorder(struct tree *root){
    if(root==NULL) printf("empty\n");
    inorder(root->left);
    printf("%d", root->data);
    inorder(root->right);
}

,但是每次调用命令时,它仅打印“空”(if语句)。所以好像我创建树的功能不起作用,或者打印功能不正确。我只想打印树中的所有值。

1 个答案:

答案 0 :(得分:1)

open NAME, "$a.nme"; insert()函数很好。

createNode()函数为树中的每个空指针打印inorder()。然后它可能崩溃,因为即使empty为null,它仍然尝试使用root->left进行递归调用。您应该只在root为空时返回。

识别哪个节点与哪个节点仍然很困难。也许您应该使用这样的代码:

root

示例输出:

#include <stdio.h>
#include <stdlib.h>

struct tree
{
    int          data;
    struct tree *left;
    struct tree *right;
};

static struct tree *createNewNode(int data)
{
    struct tree *newNode = malloc(sizeof(struct tree));
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

static struct tree *insert(struct tree *root, int data)
{
    if (root == NULL)
        root = createNewNode(data);
    else if (data < root->data)
        root->left = insert(root->left, data);
    else
        root->right = insert(root->right, data);
    return root;
}

static void pr_indent(int level)
{
    for (int i = 0; i < level; i++)
        printf("    ");
}

static void inorder(struct tree *root, int level)
{
    if (root != NULL)
    {
        inorder(root->left, level + 1);
        pr_indent(level);
        printf("%d\n", root->data);
        inorder(root->right, level + 1);
    }
}

static void print_inorder(const char *tag, struct tree *root)
{
    printf("%s: \n", tag);
    inorder(root, 0);
    putchar('\n');
}

static void release(struct tree *node)
{
    if (node != NULL)
    {
        release(node->left);
        release(node->right);
        free(node);
    }
}

int main(void)
{
    struct tree *root = NULL;
    int values[] = { 37, 24, 30,36, 72, 57, 32, 62 };
    enum { NUM_VALUES = sizeof(values) / sizeof(values[0]) };

    for (int i = 0; i < NUM_VALUES; i++)
    {
        root = insert(root, values[i]);
        char tag[20];
        snprintf(tag, sizeof(tag), "%d: After %d", i + 1, values[i]);
        print_inorder(tag, root);
    }

    release(root);
    return 0;
}