所谓的二叉树相似是指要么它们都为空或都只有一个根结点,要么它们的左右树均相似。
参考代码:
#include<iostream>
using namespace std;
struct Binode{
char data;
Binode* lchild;
Binode* rchild;
};
class Bitree{
private:
Binode* root1;
Binode* root2;
Binode* Creat(Binode* bt)
{
char ch;
cin>>ch;
if(ch=='#')
bt=NULL;
else
{
bt=new Binode;
bt->data=ch;
bt->lchild=Creat(bt->lchild);
bt->rchild=Creat(bt->rchild);
}
return bt;
}
void Release(Binode* bt)
{
if(bt!=NULL)
{
Release(bt->lchild);
Release(bt->rchild);
delete bt;
}
}
int Like(Binode *root1,Binode *root2)
{
if(root1==NULL&&root2==NULL)
return 1;
else if((root1==NULL&&root2!=NULL)||(root1!=NULL&&root2==NULL))
return 0;
else
{
int same=Like(root1->lchild,root2->lchild);
if(same)
same=Like(root1->rchild,root2->rchild);
return same;
}
}
public:
Bitree()
{
root1=Creat(root1);
root2=Creat(root2);
}
~Bitree()
{
Release(root1);
Release(root2);
}
void like()
{
cout<<Like(root1,root2)<<endl;
}
};
int main()
{
int t;
cin>>t;
while(t--)
{
Bitree A;
A.like();
}
return 0;
}