【问题标题】:runtime error : to create a binary tree运行时错误:创建二叉树
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-06-16
    • 2017-07-01
    • 1970-01-01
    • 2019-09-23
    • 2016-09-18
    • 2020-12-28
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多