二叉搜索树中的奇怪错误

时间:2011-03-20 22:47:02

标签: c++ tree binary-search-tree

#include <iostream>
using namespace std;
#define YES 1
#define NO 0

class tree
{
    private:

    public:
        struct leaf
        {
            int data;
            leaf *l;
            leaf *r;
        };
        struct leaf *p;
        tree();
        ~tree();
        void destruct(leaf *q);
        tree(tree& a);
        void add(int n);
        void transverse();
        void in(leaf *q);
        void pre(leaf *q);
        void post(leaf *q);
        leaf*  createBST(int *preOrder, int* inOrder, int len);     
};      
tree::tree()
{
    p=NULL;
}
tree::~tree()
{
    destruct(p);
}
void tree::destruct(leaf *q)
{

}

void tree::transverse()
{
    int c;
    cout<<"\n1.InOrder\n2.Preorder\n3.Postorder\nChoice: ";
    cin>>c;
    switch(c)
    {
        case 1:
            in(p);
            break;

        case 2:
            pre(p);
            break;

        case 3:
            post(p);
            break;
    }
}
void tree::in(leaf *q)
{
    if(q!=NULL)
    {
        in(q->l);
        cout<<"\t"<<q->data<<endl;
        in(q->r);
    }

}
void tree::pre(leaf *q)
{
    if(q!=NULL)
    {
        cout<<"\t"<<q->data<<endl;
        pre(q->l);
        pre(q->r);
    }

}
void tree::post(leaf *q)
{
    if(q!=NULL)
    {
        post(q->l);
        post(q->r);
        cout<<"\t"<<q->data<<endl;
    }

}



tree::leaf* tree::createBST(int *preOrder, int* inOrder, int len)
{
    int i;
    tree::leaf *bst = new tree::leaf;
//  tree bst;
//  if(len < 0)
//      {//bst = NULL;
//      return bst;}

    bst->data = *preOrder;
    for(i = 0; i < len; i++)
        if(*(inOrder + i) == *preOrder)
        break;
    if(i>=0)    
        bst->l = createBST(preOrder + 1, inOrder, i);
    if((len-i-1) >=0)
        bst->r = createBST(preOrder + i +1, inOrder + i + 1, len-i-1);
    return bst;

}

int main()
{


    tree bst;
    int pre_data[] = {20,8,4,12,10,14,22};
    int in_data[] = {4,8,10,12,14,20,22};
    bst.p = bst.createBST(pre_data, in_data, 7);
    bst.transverse();

    return 0;
}

主要问题在于功能

  tree::leaf* tree::createBST(int *preOrder, int* inOrder, int len)

注意:我已经发布了两个有关此问题的问题。因为我修改了很多代码,所以我开始了一个新帖子。

1 个答案:

答案 0 :(得分:2)

我认为错误是您的递归没有终止条件。考虑len == 0的情况,您将执行以下代码行:

bst->l = createBST(preOrder + 1, inOrder, i);

这将传递0的长度,同样的事情将再次发生。这是无限递归,会导致分段错误。

我认为通过将此问题添加到createBST的开头来解决您的问题:

if(len == 0)
    return NULL;