In place Java (without recursion) solution using Morris traversal technique.


  • 0
    V

    Its same as morris traversal but do let me know if you don't understand this.

      public void flatten(TreeNode root) {
           while(root != null){
               if(root.left != null){
                   TreeNode rightMost = root.left; // get the right most node of left child of current node.
                   while(rightMost.right != null) 
                        rightMost =  rightMost.right;
                   // pointers are changed as per required result in below 2 lines.
                   rightMost.right = root.right;
                   root.right = root.left;
                   root.left = null; // clear left not needed now.
               }
               root = root.right;
           }
        }
    

Log in to reply
 

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