Very clean Java solution


  • 2
    V

    Use stack to implement a pre-order traverse. The code is super clean!

     public class Solution {
         public void flatten(TreeNode root) {
             if(root == null)
                 return;
        
             Stack<TreeNode> stack = new Stack<TreeNode>();
             stack.push(root);
             while(!stack.isEmpty()){
                 TreeNode node = stack.pop();   
            
                 if(node.right != null)
                     stack.push(node.right);
                 if(node.left != null)
                     stack.push(node.left);
            
                 node.left = null;
                 /*   
                 *   If the stack is not empty, then the peek element 
                 *   will be the next node in pre-order traverse, 
                 *   which will be the element we need to point to.
                 */
                 if(!stack.isEmpty())
                     node.right = stack.peek();
             }
         }
     }

Log in to reply
 

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