Iterative Java solution space O(1) runtime O(N)


  • 0
    I
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void flatten(TreeNode root) {
            
            if(root == null) {
                return;
            }
            
            TreeNode tail = root;
            while(null != tail) {
                TreeNode left = tail.left;
                TreeNode right = tail.right;
                
                tail.left = null;
                if(left != null) {
                    tail.right = left;
                    while(left.right != null) {
                        left = left.right;
                    }
                    
                    left.right = right;
                }
                
                tail = tail.right;
            }
            
        }
    }
    

Log in to reply
 

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