Leetcode #114 Flatten Binary Tree to Linked List

Leetcode #114 Flatten Binary Tree to Linked List

Difficulty: Medium

This question is a bit tricky since it mentioned pre-order traversal (root, left, right) The idea here is to traverse recursively and make the "reordering" as you go.

Thought process:

  • Traverse left subtree then right subtree
  • If you encounter a left node
  • Keep the existing right node as a temp, assign left as null.
  • We need to append our previous right node to the "last new right"
    • In order to do that, we need to traverse until we find the new last right node and assign it there.

Time complexity: I'm not sure actually - might not be O(n) since there's a nested loop. Space complexity: O(1) - since there's no additional space allocated.

Link: Flatten Binary Tree to Linked List

/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function(root) {
    let temp = null;

    let traverse = (root, temp) => {
        if(!root){
            return;
        }

        if(!root.left && !root.right){
            return;
        }

        traverse(root.left, temp);
        traverse(root.right, temp);

        if(root.left){
            temp = root.right;
            root.right = root.left;
            root.left = null;
            let cur = root.right;

            while(cur!=null){
                if(cur.right){
                    cur = cur.right;    
                }

                if(cur.right == null){
                    cur.right = temp;
                    break;
                }
            }
        }
    }

    traverse(root);
};