Share my accepted java solution


  • 1
    M

    Recursive (1ms)

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

    Iterative (2ms)

    public boolean isSymmetric(TreeNode root) {
        if(root==null) return true;
        
        Queue<TreeNode> left  = new LinkedList<>();
        Queue<TreeNode> right = new LinkedList<>();
        
        left.add(root.left);
        right.add(root.right);
        while(!left.isEmpty()&&!right.isEmpty()){
            TreeNode l = left.poll();
            TreeNode r = right.poll();
            if(l == null && r == null) continue;
            if(l == null || r == null) return false;
            
            if(l.val!=r.val) return false;
            
            left.add(l.left);
            left.add(r.left);
            right.add(r.right);
            right.add(l.right);
        }
        return left.size()!=right.size()?false:true;
    }

  • 0
    W

    Iterative
    the last code: return left.size()!=right.size()?false:true;
    you can change: return left.size() == right.size();


Log in to reply
 

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