1ms recursive Java Solution, easy to understand


  • 69
    Y
     public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        return isMirror(root.left,root.right);
    }
    public boolean isMirror(TreeNode p, TreeNode q) {
        if(p==null && q==null) return true;
        if(p==null || q==null) return false;
        return (p.val==q.val) && isMirror(p.left,q.right) && isMirror(p.right,q.left);
    }

  • 0
    Y

    very nice, elegant solution!! great understanding of recursion


  • 1
    Y

    Thank you! :) I'm a green hand in programming actually.


  • 1
    D

    Thanks for your idea, this is really elegant!


  • 0
    P

    Gorgeous solution! The function isMirror is brilliant.


  • 0
    N

    wonderful solution! Really easy to understand, thank you


  • 0
    H

    good solution, easy to understand


  • 0
    H

    You solve my problem! Try to use a helper function when you can't solve it in the direct way.


  • 1
    X

    I found my solution very similar to yours, but with minor difference, which is more intuitive to myself.

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

  • 0
    G

    very easy to unstrand,thanks!


Log in to reply
 

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