【发布时间】:2015-06-10 07:40:00
【问题描述】:
#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 打印出 nil 显然意味着我的树是空的,因此下面的 printf 和递归不会运行。我无法弄清楚我哪里出错了,任何建议或答案都将不胜感激,因为我无法弄清楚为什么在 main 中调用所有这些插入后根会为空。
【问题讨论】:
-
失败的分配是否被触发了? (root) 没有意义,可能会导致问题更改为 root
标签: c binary-tree