一、题目描述
给定二叉树,检查该二叉树是否为镜像对称的。
二、输入与输出
1.输入
第一行输入t,表示有t个测试样例。
第二行起,每一行首先输入n,接着输入n个整数代表一个二叉树。依次输入t个二叉树。
数组形式的二叉树表示方法与题目:DS二叉树_伪层序遍历构建二叉树 相同,输入-1表示空结点。
结点个数 >= 1
n >= 1
1 <= 结点值 <= 1000
4
7 1 2 2 3 4 4 3
7 1 2 2 -1 3 -1 3
7 10 20 20 -1 40 40 -1
5 1 2 2 -1 3
2.输出
每一行输出二叉树是否为镜像对称。
依次输出t行。
true
false
true
false
三、参考代码
#include <iostream>
#include <string>
#include<queue>
#include<stack>
using namespace std;
class TreeNode
{
public:
int data;
TreeNode* lchild;
TreeNode* rchild;
TreeNode* parent;
TreeNode() { lchild = NULL, rchild = NULL; parent = NULL; }
TreeNode(int n) { lchild = NULL, rchild = NULL; parent = NULL; data = n; }
};
class Tree
{
public:
TreeNode* root;
int* arr;
int len;
Tree() {};
~Tree() {};
void Create()
{
root = Creat();
}
TreeNode* Creat()
{
cin >> len;
if (len == 0)
{
return NULL;
}
arr = new int[len];
for (int i = 0; i < len; i++)
{
cin >> arr[i];
}
queue<TreeNode*>q;
TreeNode* r = new TreeNode(arr[0]);
if (r)
{
q.push(r);
}
int index = 1;
while (!q.empty() && index < len)
{
TreeNode* cur = q.front();
q.pop();
if (index < len && arr[index] != -1)
{
cur->lchild = new TreeNode(arr[index]);
q.push(cur->lchild);
}
index++;
if (index < len && arr[index] != -1)
{
cur->rchild = new TreeNode(arr[index]);
q.push(cur->rchild);
}
index++;
}
return r;
}
bool pri()
{
if (root == NULL) return false;
queue<TreeNode*>q;
q.push(root->lchild);
q.push(root->rchild);
while (!q.empty())
{
TreeNode* t1 = q.front();
q.pop();
TreeNode* t2 = q.front();
q.pop();
if ( !t1 && !t2 )//都是NULL 00
{
continue;
}
if (!t1 || !t2)//一个是NULL一个不是 10/01
{
return false;
}
//只剩下11
if (t1->data != t2->data)
{
return false;
}
q.push(t1->lchild);
q.push(t2->rchild);
q.push(t1->rchild);
q.push(t2->lchild);
}
return true;
}
};
int main()
{
int sum;
cin >> sum;
while (sum--)
{
Tree t;
t.Create();
if (t.pri())
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}
return 0;
}