在二进制树插入和遍历期间,我得到了分段故障


#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 traversal效果很好。

在您的范围内,当您调用插入insert(root, arr[i])时,您只需要i而不是arr[i]。因此,将其更改为insert(root, i);

最新更新