Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
方法一
递归实现
如果一个二叉树是对称树,则说明它的左右子树有相同的根节点,并且左子树的左孩子等于右子树的右孩子,左子树的右孩子等于右子树的左孩子。
根据这些特点,很容易能写出满足是对称树的条件以及不满足是对称树的条件,并进行判断。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root,root);
}
private boolean isMirror(TreeNode root1,TreeNode root2)
{
if(root1==null&&root2==null)
return true;
if(root1==null||root2==null)
return false;
return (root1.val==root2.val)&&isMirror(root1.left,root2.right)&&isMirror(root1.right,root2.left);
}
}
方法二
迭代实现
借助一个队列来完成。
每次从头取出两个节点进行判断,如果当前判断的两个节点满足对称树的条件,则按第一个节点的左孩子、第二个节点的右孩子、第一个节点的右孩子、第二个节点的左孩子的顺序存入队列中;如果当前判断的两个节点不满足对称树的条件,则直接返回false。
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
queue.add(root);
while(!queue.isEmpty())
{
TreeNode node1=queue.poll();
TreeNode node2=queue.poll();
if(node1==null&&node2==null)
continue;
if(node1==null||node2==null)
return false;
if(node1.val!=node2.val)
return false;
queue.add(node1.left);
queue.add(node2.right);
queue.add(node1.right);
queue.add(node2.left);
}
return true;
}
}
注:poll方法为取出并返回该链表的第一个元素。