Clean 1ms Java solution


  • 3
    C
    public boolean isSymmetric(TreeNode root) {
        if(root == null){
            return true;
        }
        
        return compare(root.left, root.right);
    }
    
    private boolean compare(TreeNode ln, TreeNode rn){
        if (ln == null || rn == null) {
            return !(ln == null ^ rn == null);
        }
    
        boolean leftResult = compare(ln.left, rn.right);
        boolean rightResult = compare(ln.right, rn.left);
    
        if (!(leftResult && rightResult)) {
            return false;
        }
    
        return ln.val == rn.val;
    }

  • 1
    L

    Slightly simplified:

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.