【发布时间】:2019-09-21 16:31:30
【问题描述】:
我正在尝试编写一个程序来构建二叉搜索树并在其一侧打印树。将用户的输入读取为整数序列,并输出基于深度缩进的树,每行有一个值。但是,我的代码正在运行,但没有在控制台上打印任何内容? 我认为我的插入功能可能有问题,但我不确定。
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left, *right;
};
typedef struct node node;
node *insert(node *t, int a){ //insert values in tree
node* tmp= (node*)malloc(sizeof(node));;
if (t==NULL) {
tmp->data = a;
tmp->left = NULL;
tmp->right = NULL;
return(tmp);
}
else if (a < t->data)
t->left = insert(t->left,a);
else
t->right = insert(t->right,a);
return(t);
}
void print( node *t, int depth) {
int i;
if (t == NULL)
return;
print(t->right, depth + 1);
for (i = 0; i < 4 * depth; ++i)
printf(" ");
printf("%d\n", t->data);
print(t->left, depth + 1);
}
int main() {
node *root= NULL;
int n,a,i;
printf("Enter number of values "); //7
scanf("%d", &n);
printf("\nEnter numbers "); //10 6 14 4 8 12 16
for (i = 0; i < n; ++i) {
scanf("%d", &a);
insert(&root, a);
}
print(root, 0);
return 0;
}
Input: 10 6 14 4 8 12 16
Expected output:
16
14
12
10
8
6
4
【问题讨论】:
-
一个快速的问题,我看到你没有在任何地方分配
insert()的返回指针。所以root始终为空。并且不要忘记free分配的内存。
标签: c pointers tree binary-tree nodes