为什么这个二叉搜索树导致堆栈溢出?

时间:2012-03-27 08:13:48

标签: c++ binary-search-tree

#include<iostream>
using namespace std;
/*main  idea  is to construct ordered statistic tree,which is  similar of
binary search tree,width addition of  one key,which shows us it's rank in given  
tree,for this i introduced additional one key-rank
*/
struct node
{
    int val;
    node *left,*right;
    int rank;
    node(int t) { val=t;left=right=NULL;}


};
node *root;
void insert(node *p,int ele)
{
    if(p==NULL){
        p=new node(ele);
        return ;


    }
    else if(ele<p->val)
    {
        insert(p->left,ele);

    }
    else if(ele>p->val)
    {
        insert(p->right,ele);

    }

}
void inorder (node *p)
{
    if(p!=NULL){ inorder(p->left);
    cout<<p->val<<" "<<p->rank;
    inorder(p->right);
    }

}
int count_node(node *t)
{
    int sum=0;
    if(t==NULL) return 0;
    else sum=1;
    if(t->left) sum+=count_node(t->left);
    if(t->right) sum+=count_node(t->right);
    return sum;
}

int main()
{
    root=NULL;
    root->rank=0;
    insert(root,26);
    insert(root,17);
    insert(root,41);
    insert(root,14);
    insert(root,30);
    insert(root,21);
    insert(root,47);
    insert(root,10);
    insert(root,16);
    insert(root,28);
    insert(root,38);
    insert(root,35);
    insert(root,39);
    insert(root,19);
    insert(root,21);
    insert(root,20);
    insert(root,7);
    insert(root,12);
    insert(root,3);
    inorder(root);

    return 0;
}

这段代码导致溢出,但我不明白为什么,因为我已经正确构造了构造函数。

4 个答案:

答案 0 :(得分:3)

问题是:

root=NULL;
root->rank=0;

这会导致未定义的行为,因为您取消引用NULL指针。任何事情都可能发生。

此外:

void insert(node *p,int ele)
{
    if(p==NULL){
        p=new node(ele);
        return ;


    }
    //...
}

这不会修改原始指针。如果您在insert指针上调用NULL,则函数返回时将为NULL。您需要通过引用传递它:

void insert(node *& p,int ele)

答案 1 :(得分:3)

除了Luchian所说的,你也有这个问题:

void insert(node *p,int ele)
{
    if(p==NULL){
        p=new node(ele);
        return ;
    }
....

指针p按值传递。当您说p=...时,您正在更改仅对该函数可见的指针副本。您可能需要reference指向您正在更改的指针:

void insert(node *&p, int ele){ ... }

答案 2 :(得分:1)

main函数的前两行有一个非常大的问题:

root=NULL;
root->rank=0;

如果您查看上面的定义,root被定义为节点指针,即它不会为实际节点保留任何空间。

如果你没有自己预留空间,那么你试图通过未初始化的内存来写。更重要的是,你明确地说根指向 nothing ,即NULL。在下一行中,您尝试访问名为rank的成员。

你应该尝试更换一行:

root = NULL;

使用

root = new node(0);

或类似的实际保留空间并构造节点的东西。

或者,您可以尝试在最后确定根目录的等级,因为如果不存在,insert函数实际构造了根。 编辑,如Luchian所说,您只需尝试insert方法中构建根。如果你按照他建议的方式重新编写insert方法,那么如果只是将root->rank=0;行移动到插入过程的末尾,那么它可能都会起作用。

答案 3 :(得分:0)

root=NULL;
root->rank=0;

这可能是问题,你不应该尊重NULL对象。

相关问题