Java Iterative Solution


  • 0
    A
       if (root == null) {
           return null;
       }
       
       Queue<TreeNode> q = new LinkedList<TreeNode>();
       q.offer(root);
       
       while (!q.isEmpty()) {
           TreeNode polled = q.poll();
           
           if (polled.left != null || polled.right != null) {
               
               TreeNode temp = polled.left;
               polled.left = polled.right;
               polled.right = temp;
               
               if (polled.left != null) q.offer(polled.left);
               if (polled.right != null) q.offer(polled.right);
               
           }
           
       }
       
       return root;

Log in to reply
 

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