【发布时间】:2012-11-30 19:32:17
【问题描述】:
我是编码新手,我正在尝试从数组中创建一个二叉树。当我尝试运行它时,出现运行时错误。有人可以解释这段代码有什么问题。 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);
}
【问题讨论】:
-
当程序崩溃时,您的第一反应应该是在调试器中运行它。它会告诉您崩溃在哪里,向您显示函数调用堆栈,并让您检查变量以帮助您了解崩溃可能发生的原因。
标签: c pointers binary-tree