给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
这题我刚开始想的是用中序遍历之后放入一个数组中,然后从中间开始比较数字是否相等。后来发现不对,会存在即使中序序列对称,但树状结构不对称的情况比如如下两种。所以还是安心按照结构来比对的好
// 5 1
// / \ / \
// 4 1 2 2
// / \ / \ / /
// -1 1 -1 4 2 2
// / \ / \
// 2 -1 2 -1
1.递归法
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
return judge(root, root);
}
bool judge(TreeNode *p1, TreeNode *p2)
{
if(p1 == NULL && p2 == NULL) return true;
if(p1 == NULL || p2 == NULL) return false;
if(p1 -> val != p2 -> val) return false;
return (p1 -> val == p2 -> val)
&& judge(p1 -> left, p2 -> right)
&& judge(p1 -> right, p2 -> left);
}
思路:这里引用评论里一位网友的思路
2.利用队列实现两两互相比对
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
queue<TreeNode*> que;
que.push(root);
que.push(root);
while(!que.empty())
{
TreeNode *p1 = que.front();
que.pop();
TreeNode *p2 = que.front();
que.pop();
if(p1 == nullptr && p2 == nullptr) continue;
if(p1 == nullptr || p2 == nullptr) return false;
if(p1 -> val != p2 -> val) return false;
que.push(p1 -> left);
que.push(p2 -> right);
que.push(p1 -> right);
que.push(p2 -> left);
}
return true;
}
队列中每两个连续的结点应该是相等的,而且它们的子树互为镜像。最初,队列中包含的是 root 以及 root。该算法的工作原理类似于 BFS,但存在一些关键差异。每次提取两个结点并比较它们的值。然后,将两个结点的左右子结点按相反的顺序插入队列中。当队列为空时,或者我们检测到树不对称(即从队列中取出两个不相等的连续结点)时,该算法结束。