2020年3月20日
Symmetric Tree
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  3But the following [1,2,2,null,3,null,3] is not:
    1
   /   2   2
   \      3    3Note:
Bonus points if you could solve it both recursively and iteratively.
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
    1
   /   2   2
 / \ / 3  4 4  3但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
    1
   /   2   2
   \      3    3说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
如果一个树的左右子树是镜像对称的,那么这个树是对称的
如果同时满足以下条件,两个树互为镜像:
public boolean isSymmetric(TreeNode root){
    return isMirror(root,root);//省略了处理root
}
public boolean isMirror(TreeNode t1,TreeNode t2){
    if(t1==null&&t2==null) return true;
    if(t1==null || t2==null) return false;
    return(t1.val==t2.val)
        && isMirror(t1.right,t2.left)
        && isMirror(t1.left,t2.right);
}时间复杂度分析
除了递归的方法,我们也可以利用队列进行迭代,队列中每两个连续的结点应该是相等的,而且他们的子树互为镜像.最初,队列中包含的是root以及root.该算法的工作原理类似于BFS,但存在一些关键差异,每次提取两个结点并比较它们的值.然后,将两个结点的左右子节点按相反的顺序插入队列中,当队列为空时,或者我们检测到树不对称(即从队列中取出两个不相等的连续结点)时,该算法结束
public boolean isSymmetric(TreeNode root){
    Queue<TreeNode> q=new linkedList<>();
    q.add(root);
    q.add(root);
    while(!q.isEmpty()){
        TreeNode t1=q.poll();
        TreeNode t2=q.poll();
        if(t1==null&&t2==nll)continue;
        if(t1==null || t2==null)return false;
        if(t1.val!=t2.val)return false;
        q.add(t1.left);
        q.add(t2.right);
        q.add(t1.right);
        q.add(t2.left);
    }
    return true;
}原文:https://www.cnblogs.com/ningdeblog/p/12541998.html