- 论坛徽章:
- 0
|
请教各位高手...
//输出从根到指定值间的所有元素
#include <iostream>
#include <assert.h>
using namespace std;
template<class Telem> class Btree;
template<class Telem>
class BtreeNode
{
private:
Telem data;
BtreeNode<Telem>* lchild;
BtreeNode<Telem>* rchild;
friend class Btree<Telem>;
public:
BtreeNode(Telem el=0,BtreeNode<Telem>* l=NULL,BtreeNode<Telem>* r=NULL):data(el),lchild(l),rchild(r)
{
}
void setdata(Telem el)
{
data=el;
}
void setlchild(BtreeNode<Telem>* l)
{
lchild=l;
}
void setrchild(BtreeNode<Telem>* r)
{
rchild=r;
}
Telem getdata()
{
return data;
}
BtreeNode<Telem>* getlchild()
{
return lchild;
}
BtreeNode<Telem>* getrchild()
{
return rchild;
}
};
template<class Telem>
class Btree
{
private:
BtreeNode<Telem>* root;
Telem* a;
int n;
BtreeNode<Telem>* build(int i);
BtreeNode<Telem>* a1[10];
int i;
public:
Btree();
Btree(Telem a[],int n);
void test(BtreeNode<Telem>* p,Telem a,BtreeNode<Telem>* array[]);
void test(Telem x);
};
template<class Telem>
Btree<Telem>::Btree()
{
root=NULL;
}
template<class Telem>
Btree<Telem>::Btree(Telem a[],int n)
{
this->a=a;
this->n=n;
root=build(1);
}
template<class Telem>
BtreeNode<Telem>* Btree<Telem>::build(int i)
{
BtreeNode<Telem>* p;
int l=2*i; int r=2*i+1;
if(i<=n && a[i-1]!=0)
{
p=new BtreeNode<Telem>();
p->data=a[i-1];
p->lchild=build(l);
p->rchild=build(r);
return p;
}
else
return NULL;
}
template<class Telem>
void Btree<Telem>::test(Telem x)
{
for(int m=0;m<10;m++)
{
a1[m]=NULL;
}
i=0;
test(root,x,a1);
for(int j=0;a1[j]!=NULL;j++) //输出数组中的元素 (1)
cout << a1[j]->data << " ";
cout << endl;
}
template<class Telem>
void Btree<Telem>::test(BtreeNode<Telem>* p,Telem a,BtreeNode<Telem>* array[])
{
array[i]=p;
i++;
if(p->data == a)
{
for(int j=0;j<i;j++) //输出数组中的元素 (2)
cout << array[j]->data << " ";
cout << endl;
}
if(p->lchild != NULL)
test(p->lchild,a,array);
if(p->rchild != NULL)
test(p->rchild,a,array);
i--;
}
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,10};
Btree<int> b(a,10);
b.test(9);
system("PAUSE");
return 0;
} |
问题:
原程序只有(1)处输出 结果不对之后 就在(2)处也加了输出( (2)处本来只有return; 跳出递归 )
为什么(1)结果不对 (2)对 ? |
|