java solution 2ms


  • 0
    S
    public boolean isSymmetric(TreeNode root){
            if(root == null){
                return true;
            }
            Queue<TreeNode> nodes = new LinkedList<>();
            if(root.left != null && root.right != null){
                nodes.add(root.left);
                nodes.add(root.right);
            }else if(root.left != null || root.right != null){
                return false;
            } else{
                return true;
            }
            
            while(!nodes.isEmpty()){
                TreeNode tree1 = nodes.poll();
                TreeNode tree2 = nodes.poll();
                if(tree1 == null && tree2 == null){
                    continue;
                }
                else if(tree1 == null || tree2 == null){
                    return false;
                }
                else if(tree1.val != tree2.val ){
                    return false;
                }
                nodes.add(tree1.left);
                nodes.add(tree2.right);
                nodes.add(tree1.right);
                nodes.add(tree2.left);
            }
            
            return true;
        }
    

Log in to reply
 

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