Java Self-Explanatory 1ms Recursive Solution


  • 3
    C
    public class Solution {
        public boolean isSymmetric(TreeNode root) {
            if(root==null)
                return true;
            return isSymSubTree(root.left, root.right);
        }
        
        public boolean isSymSubTree(TreeNode left, TreeNode right){
            if(left==null)
                return (right==null);
            if(right==null)
                return false;
             return (left.val==right.val) && isSymSubTree(left.left,right.right) && isSymSubTree(left.right,right.left);
        }
    }

  • 0
    V
        if(left==null)
            return (right==null);
        if(right==null)
            return false;
    

    Hey OP,

    Why are left is null and right is null handled differently? Just wonder.


  • 0
    C

    What would you prefer:

    if(left==null)
    return (right==null);
    if(right==null)
    return false;

    OR

    if(left==null && right==null)
          return true;
    if(left==null || right==null)
          return false;
    

    You can use any one of them. But I usually prefer the first one. More concise. You are free to write the second one as well.

    Happy Coding :)


Log in to reply
 

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