题目描述
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
判断是否为对称二叉树
样例
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
思路分析
在比较相同二叉树(Same Tree)的基础上,更改了判断条件。
即 上题是先序遍历,比较每个节点的值,此题同样是遍历,却是左子树与右子树比较,左子树的左子树与右子树的右子树比较,右子树的左子树与左子树的右子树比较(说起来有些抽象,配合图看),满足条件即是对称二叉树
代码
方法一:递归
public boolean isSymmetric(TreeNode root) {
return isSymmetric(root, root);
}
public boolean isSymmetric(TreeNode root1,TreeNode root2){
if (root1==null && root2==null) { //都为空 即相等
return true;
}
if (root1==null || root2==null) { //任一为空 不满足条件 终止遍历
return false;
}
if (root1.val == root2.val) { //左子树与对应右子树比较,右子树同理,相等则继续遍历
return isSymmetric(root1.left, root2.right) && isSymmetric(root1.right, root2.left);
}
return false;
}
结果
方法二:循环写法 层序遍历
public boolean isSymmetric(TreeNode root) {
return isSymmetric(root,root);
}
public boolean isSymmetric(TreeNode p,TreeNode q) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(p);
queue.offer(q);
while ( !queue.isEmpty() ){
TreeNode temp1 = queue.poll();
TreeNode temp2 = queue.poll();
if (temp1==null && temp2==null) {
continue;
}
if (temp1==null || temp2==null || temp1.val != temp2.val) {
return false;
}
queue.offer(temp1.left);
queue.offer(temp2.right);
queue.offer(temp1.right);
queue.offer(temp2.left);
}
return true;
}
结果