使用二叉树

时间:2015-04-05 21:11:27

标签: c binary-tree

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

typedef struct node_{
    int val;
    struct node_ *left;
    struct node_ *right;
}node;

node* insert(node* root,int val);
void inorder(node* root);
int main(void)
{
    int i;
    int item;
    node* root = NULL;

    srand(time(NULL));

    for( i = 0; i < 10; i++)
    {
        item = rand()%15;
        insert(root,item); 
    }

    inorder(root);

    return 0;    
}

node* insert(node* root,int val)
{
    if(root == NULL)
    {
        root = malloc(sizeof(node));
        if(root!= NULL)
        {
            (root)->val = val;
            (root)->left = NULL;
            (root)->right = NULL;
        }
        else 
            printf("%d not inserted. No memory available.\n",val);
    }
    else
    {
        if(val < (root)->val)
        {
            insert((root->left),val);
        }

        if(val>root->val)
        {
            insert(((root)->right),val);
        }
    }
}

void inorder(node* root)
{
    printf("%p",root);
    if(root != NULL)
    {
        inorder(root->left);
        printf("%3d",root->val);
        inorder(root->right);
    }
}

我正在尝试创建二叉树并按顺序打印出值。但是,当我运行此代码时,地址的printf打印出来,显然意味着我的树是空的,因此下面的printf和递归不会运行。我无法弄清楚我哪里出错了,任何建议或答案都会受到赞赏,因为我无法弄清楚为什么在调用main中的所有插入后root将为null。

2 个答案:

答案 0 :(得分:0)

在声明和初始化root(main())之后的node* root = NULL;中,您永远不会分配它。为了解决这个问题,您应该将林insert(root,item);更改为root = insert(root,item);

另请注意,虽然insert被定义为返回node *,但它不会返回任何值。

答案 1 :(得分:0)

您将root作为参数传递给insert()(表示它会返回一些但不会返回的内容)。在insertmalloc您的节点并将其分配给本地变量root。你做过的任何事情都不会使它成为insert函数。

尝试从insert或使用全局root返回内容。

正如@JoshuaByer在下面的评论中暗示的那样,另一种方法是让你的insert方法“通过引用传递”,这样它就可以有效地修改传递给它的内容。

void insert(node** rootp,int val)
{
    if(*rootp == NULL)
    {
        *rootp = malloc(sizeof(node));
    }
    /* and so on */

如果您不明白这是什么意思,谷歌“通过引用C传递”,我很肯定你会得到一些很好的信息。