• 2.11
    • 要判断整棵树是否为对称树,所以必须要辅助函数!
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root.left==null&&root.right==null) return true;
        if(root.left==null||root.right==null) return false;
        if(root.left.val!=root.right.val) return false;
        return isSymmetric(root.left)&&isSymmetric(root.right);
    }
}
  • 1.26
    • 一般,忘记最后,进入递归前,需要判断节点的值是否相等了
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return check(root.left,root.right);
    }
    public boolean check(TreeNode left,TreeNode right){
        if(left==null&&right==null) return true;
        if(left!=null&&right==null) return false;
        if(left==null&&right!=null) return false;
        if(left.val!=right.val) return false;
        return check(left.left,right.right)&&check(left.right,right.left);
    }
}
  • 11.16
    • 忘得有点多,第一就是忘了需要辅助函数,因为原函数只能判断一棵树,而题目是需要两棵树的第一课树的左节点和第二颗树的右节点。
    • 第二就是判断递归条件是节点为 null,而不是节点的 val 值为 null
    • 第三个就是,当左右对称时,不能返回 true,而是最终 return 时返回与运算的两个递归
    • 最后的与运算递归应该是两棵树对称的节点,而不是一个树的左右节点
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return check(root.left,root.right);
    }
    public boolean check(TreeNode left,TreeNode right){
        if(left==null && right==null){
            return true;
        }
        if(left==null || right==null){
            return false;
        }
        if(left.val!=right.val){
            return false;
        }
        return check(left.left,right.right)&&check(left.right,right.left);
    }
}
  • 11.11
    • 有点意思,与运算一起判断
    • 在递归前判空时看时一起为空,还是其中一个为空,返回boolean值
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return check(root.left,root.right);
    }
 
    public boolean check(TreeNode p,TreeNode q){
        if(p==null&&q==null){
            return true;
        };
        if(p==null||q==null){
            return false;
        }
        return p.val==q.val&&check(p.left,q.right)&&check(p.right,q.left);
    }
}

最后会通过与运算来一起判断是否为对称树

true && true && truetrue