简体   繁体   English

二叉搜索树未排序数组

[英]binary search tree unsorted array

I have a problem trying to insert elements on my BST given an unsorted array. 给定未排序的数组,尝试在BST上插入元素时遇到问题。 The output gives me a segmentation fault, but I can't pinpoint the location of my error. 输出给我一个分段错误,但是我无法查明错误的位置。 I'm pretty sure that something is wrong with my insert, but I'm not sure what. 我很确定插入内容出了点问题,但是不确定。 If anyone can give me insight that would be much appreciated. 如果有人可以给我见识,将不胜感激。

#include <iostream>

using namespace std;

struct BST{
    BST* left;
    BST* right;
    int data;
};

BST* init(int data){
    BST* a = new BST;
    a->data = data;
    a->right = NULL;
    a->left = NULL;
    return a;
}

BST* insert(BST* root, int data){
    if (root == NULL)
        root = new BST;
    else{
        BST* current = root;
        if (current->data >= data)
            insert(current->right, data);
        else
            insert(current->left, data);
    }
    return 0;
}

void inorderTraversal(BST* root)
{
    if(root == NULL) 
        cout << "No node" << endl;
    inorderTraversal(root->left);
    cout << root->data << endl;
    inorderTraversal(root->right);
}


int main(){
    BST* tree = init(5);
    int a[8] = {1, 3, 5, 6, 3, 9, 10, 46};
    cout << "seg fault" << endl;
    for (unsigned int i = 0; i < sizeof(a); i++)
        insert(tree, a[i]);
    cout << "seg fault here" << endl;

}

Actually, I think the problem is in your for loop. 实际上,我认为问题出在您的for循环中。 You are looping too far. 您循环得太远了。 Try using a.size() instead of sizeof(a) . 尝试使用a.size()而不是sizeof(a) With sizeof(a) you are requesting the size of the array in bytes, which is probably returning 32. 使用sizeof(a)您需要以字节为单位的数组大小,这可能返回32。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM