Yet another Java iterative O(1) space solution


  • 0
    J

    I get the idea from Morris traversal.

    public class Solution {
        public void flatten(TreeNode root) {
            while (root != null) {
                if (root.left == null) {
                    root = root.right;
                } else {
                    TreeNode next = root.left;
                    TreeNode tail = next;
                    while (tail.right != null) tail = tail.right;
                    tail.right = root.right;
                    root.right = next;
                    root.left = null;
                    root = next;
                }
            }
        }
    }
    

Log in to reply
 

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