Weird error in binary search tree [closed]
#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-&g开发者_开发百科t;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;
}
The main problem is in function
tree::leaf* tree::createBST(int *preOrder, int* inOrder, int len)
Note: I've posted two questions about this. Because I modified my code a lot I started a fresh post.
I believe the error is that you have no terminating condition for your recursion. Consider the case where len == 0
, you will execute this line of code:
bst->l = createBST(preOrder + 1, inOrder, i);
This will pass in a length of 0 and the same thing will happen again. This is infinite recursion, and will cause a segmentation fault.
I think your problem is solved by adding this to beginning of createBST
:
if(len == 0)
return NULL;
精彩评论