0

我是编码新手,我试图从数组中创建一个二叉树。当我尝试运行它时,出现运行时错误。有人可以解释这段代码有什么问题。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);
    }
4

1 回答 1

0

你的内在while永远不会被执行,因为它被初始化root并且永远不会被取消。我想你会想要在循环的每次迭代中while(traverse == NULL)替换while(traverse != NULL)并重置traverse回(完成后)。rootforwhile

于 2012-11-30T11:26:49.043 回答