Java 1ms 4-liner recursive, so easy to understand that no explanation is needed


  • 0
    public class Solution {
        public boolean isSymmetric(TreeNode root) {
            return isSymmetric(root, root);
        }
        
        private boolean isSymmetric(TreeNode left, TreeNode right) {
            if (left == null && right == null) return true;
            if ((left == null && right != null) ||(right == null && left != null)) return false;
            return (left.val != right.val) ? false : (isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left));
        }
    }
    

  • 1
    O

    Brilliant! But I think you can still simplify your code, like this:

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

  • 0
    L

    Your code has done some duplicate work, return isSymmetric(root,root),then it will execute isSymmetric(root.left,root.right) and isSymmetric(root.right,root.left),Actually they are same.
    you should writes like following:
    public boolean isSymmetric(TreeNode root) {
    if(root==null)
    return true;
    return isSymmetric(root.left,root.right);

    }

  • 0

    @liuzhisheng1226
    Good point. I agree.


Log in to reply
 

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