在二叉树插入和遍历期间,我得到一个分段故障

时间:2017-06-29 04:00:33

标签: c++ binary-tree

#include <iostream>

struct node {
    int val;
    node * left, * right;

    node(int value) : val(value), left(NULL), right(NULL) {}
};
void insert(node * &root, int val) {
        if(!root)
            root = new node(val);
        else {
            if(val <= root->val)
                insert(root->left, val);
            else
                insert(root->right, val);
        }
}

void inorder(node *root) {
    if(root == NULL)
        return ;

    inorder(root->left);
    std::cout << root->val << " ";
    inorder(root->right);
}

int main(){ 
    node *root = NULL;
    int arr[] = {7,3,8,6};

    for(auto i:arr)
        insert(root, arr[i]);
    inorder(root);
    std::cout << std::  endl;

    return 0;
}

所有这些都是使用gcc 5.4.0在ubuntu 16.04.1上用c ++ 11编译的 该程序给我一个分段错误。但是,当我在树中手动创建新节点时,inorder遍历工作正常。

1 个答案:

答案 0 :(得分:1)

在您的范围内,当您拨打insert(root, arr[i])时,您只需要i,而不是arr[i]。因此,简单地将其更改为insert(root, i);