#include<iostream>
using namespace std;
const int Maxsize = 20;
struct Node {
char Data;
int Left, Right;
}T1[Maxsize], T2[Maxsize];
typedef struct Node Tree;
int check[Maxsize];
void Initialize(Tree T[])
{
for (int i = 0; i < Maxsize; i++)
{
T[i].Left = T[i].Right = -1;
}
}
void Intializecheck(int check[])
{
for (int i = 0; i < Maxsize; i++)
check[i] = 0;
}
int Read(Tree T[], int N)
{
for (int i = 0; i < N; i++)
check[i] = 0;
if (N == 0)return -1;
Initialize(T);
char left, right;
for (int i = 0; i < N; i++)
{
cin >> T[i].Data;
cin.get();
cin >> left;
cin.get();
if (left != '-')
{
T[i].Left = left - '0';
check[T[i].Left] = 1;
}
else T[i].Left = -1;
cin >> right;
cin.get();
if (right != '-')
{
T[i].Right = right - '0';
check[T[i].Right] = 1;
}
else T[i].Right = -1;
}
int i;
for (i = 0; i < N; i++)
if (!check[i])break;
return i;
}
bool Isomo(int root1, int root2)
{
if (root1 == -1 && root2 == -1)return true;//都是空树
if ((root1 == -1 && root2 != -1) || (root1 != -1 && root2 == -1))return false;//一个空树一个不空
if (T1[root1].Data != T2[root2].Data)return false;//根节点都存在但数值不同
if (T1[root1].Left != -1 && T2[root2].Left != -1 && T1[T1[root1].Left].Data == T2[T2[root2].Left].Data)
return Isomo(T1[root1].Right, T2[root2].Right);//左子树都存在且值相等,判断右子树
else//子树互换比较
return(Isomo(T1[root1].Right, T2[root2].Left) && Isomo(T1[root1].Left, T2[root2].Right));
}
int main()
{
int N1, N2;
cin >> N1;
cin.get();
int root1 = Read(T1, N1);
cin >> N2;
cin.get();
int root2 = Read(T2, N2);
if (Isomo(root1, root2))cout << "Yes" << endl;
else cout << "No" << endl;
cin.get();
return 0;
}
一、关于cin,在建树时,输入的有数字也有字符,一开始直接cin>>left,这样会出错,当输入‘-’时,出错后cin将不会继续读入后续的输入,这里要十分注意
二、关于代码
T[i].Right = right - '0'; check[T[i].Right] = 1;
提供了一种采集数字符号混合的方式,即先全部读为字符,之后再转换。同样这里也出现了一个类似的问题,check读入有问题的数字之后,后面的check将不能再进行赋值
运行截图如下