【数据结构与算法】二叉树——对称二叉树

对称二叉树

LeetCode:对称二叉树

题目描述:

给定一个二叉树,检查它是否是镜像对称的。

示例:

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3
返回true

思想:

1.怎么判断一棵树是不是对称二叉树? 答案:如果所给根节点,为空,那么是对称。如果不为空的话,当他的左子树与右子树对称时,他对称

2.那么怎么知道左子树与右子树对不对称呢?在这我直接叫为左树和右树 答案:如果左树的左孩子与右树的右孩子对称,左树的右孩子与右树的左孩子对称,那么这个左树和右树就对称。

仔细一想就明白了,递归写起来很简单。

代码

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        return isSonSymmetric(root.left, root.right);
    }
    private boolean isSonSymmetric(TreeNode m, TreeNode n){
        if(m==null&&n==null)
            return true;
        if(m==null||n==null||m.val!=n.val)
            return false;
        return isSonSymmetric(m.left,n.right)&&isSonSymmetric(m.right,n.left);
    }
}

猜你喜欢

转载自www.cnblogs.com/buptleida/p/12730346.html