例如,下面二棵樹圖(1)就是對稱的二叉樹,而圖(2)(3)就不是的。
具體是實現代碼如下:
#include <iostream>
using namespace std;
struct BinaryTree
{
int data;
BinaryTree *pLeft;
BinaryTree *pRight;
};
BinaryTree *pRoot1=NULL;
BinaryTree *pRoot2=NULL;
BinaryTree *pRoot3=NULL;
void CreateTree(BinaryTree * &root)
{
int data;
cin>>data;
if(0==data)
root=NULL;
else
{
root=new BinaryTree;
root->data=data;
//前序遍歷構建二叉樹;
CreateTree(root->pLeft);
CreateTree(root->pRight);
}
}
bool IsSymmetricalHelp(BinaryTree *root1,BinaryTree *root2)
{
if(root1==NULL && root2==NULL)
return true;
if(root1==NULL || root2==NULL)//把null也算上,很重要,防止數據一樣的特殊情況;
return false;
if(root1->data!=root2->data)
return false;
return IsSymmetricalHelp(root1->pLeft,root2->pRight)
&& IsSymmetricalHelp(root1->pRight,root2->pLeft);
}
bool IsSymmetrical(BinaryTree *root)
{
return IsSymmetricalHelp(root,root);
}
void PreOrder(BinaryTree *root)
{
if(root)
{
cout<<root->data<<" ";
PreOrder(root->pLeft);
PreOrder(root->pRight);
}
}
void UntiPreOrder(BinaryTree *root)
{
if(root)
{
cout<<root->data<<" ";
PreOrder(root->pRight);
PreOrder(root->pLeft);
}
}
int main()
{
bool result=false;
CreateTree(pRoot1);
cout<<"樹1的--前序遍歷:";
PreOrder(pRoot1);
cout<<endl;
cout<<"樹1的反前序遍歷:";
UntiPreOrder(pRoot1);
result=IsSymmetrical(pRoot1);
if(result)
cout<<endl<<"該樹是對稱樹!"<<endl;
else
cout<<"該樹不是對稱樹!"<<endl;
cout<<endl;
CreateTree(pRoot2);//樹3雖然遍歷一樣,但是不是對成樹!
cout<<"樹2的--前序遍歷:";
PreOrder(pRoot2);
cout<<endl;
cout<<"樹2的反前序遍歷:";
UntiPreOrder(pRoot2);
cout<<endl;
result=IsSymmetrical(pRoot2);
if(result)
cout<<"該樹是對稱樹!"<<endl;
else
cout<<"該樹不是對稱樹!"<<endl;
cout<<endl;
system("pause");
return 0;
}
運行結果如下;