我是编码的新手,我试图创建一个从数组中获得的二叉树。当我尝试运行它时,我收到运行时错误。有人可以解释这段代码有什么问题。 tnode是用于存储节点的结构,并且调用construct_tree来构建树。
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
struct tnode{
int value;
struct tnode *parent ;
struct tnode *left;
struct tnode *right;
};
typedef struct tnode node;
node* construct_tree(int *a,int n){
printf("where");
node *root, *temp, *traverse, *traverse_parent;
root = (node*)malloc(sizeof(node));
root->value = a[0];
root->parent = NULL;
root->left = NULL;
root->right = NULL;
traverse = root;
printf("where1");
printf("\n%d",a[0]);
int i=0;
for(i=1;i<n;i++){
temp = (node*)malloc(sizeof(node));
temp->value = a[i];
temp->left = NULL;
temp->right = NULL;
while(traverse == NULL){
traverse_parent = traverse;
if(traverse->value < a[i]) traverse = traverse->right;
else traverse = traverse->left;
}
temp ->parent = traverse_parent;
printf("\n a[i]: %d and parent : %d",a[i],traverse_parent->value);
}
return root;
}
int main(){
int a[] = {5,3,7,6,11,1,4};
node* root;
printf("where2");
root = construct_tree(a,6);
//tree_traversal(root);
}
答案 0 :(得分:0)
您的内部while
永远不会被执行,因为它已初始化为root
且永远无效。我想您希望将while(traverse == NULL)
替换为while(traverse != NULL)
,并在traverse
循环的每次迭代中将root
重置为for
(在{{之后) 1}}完成)。