leetcode打卡day20

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

思路:递归法,比较左子树和右子树是否相等,比较left的左节点和right的右节点,再比较left的右节点和right的左节点。

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

执行用时 :1 ms, 在所有 Java 提交中击败了46.16%的用户
内存消耗 :38.4 MB, 在所有 Java 提交中击败了11.76%的用户

发布了20 篇原创文章 · 获赞 2 · 访问量 273

猜你喜欢

转载自blog.csdn.net/weixin_46442834/article/details/104997093
今日推荐