28 对称的二叉树

NowCoder

题目描述

请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

【剑指Offer】28 对称的二叉树_其他

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    boolean isSymmetrical(TreeNode pRoot) {
        if(pRoot == null)
            return true;
        
        return isSymmetrical(pRoot.left, pRoot.right);
    }
    // 判断镜像
    private boolean isSymmetrical(TreeNode l, TreeNode r) {
        if(l == null && r == null)
            return true;
        if(l == null || r == null)
            return false;
        if(l.val != r.val)
            return false;
        
        return isSymmetrical(l.left, r.right) && isSymmetrical(r.left, l.right);
    }
}