Journal Archive

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function(root) {
    
    // use DFS to flat left and right subtree
    const toFlat = (root) => {
        if (!root) return null;
        
        let left, right;
        
        if (root.left) {
            left = toFlat(root.left);
        }
        
        if (root.right) {
            right = toFlat(root.right);
        }
        // if there's a left subtree insert between root
        // and right subtree
        if (left) {
            left.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        // return the tail of the flatten subtree
        let tail = right || left || root;
        return tail;
    }
    
    toFlat(root);
};

Day 28: Solving one of LeetCode problems

114. Flatten Binary Tree to Linked List Difficulty - Medium

Given the root of a binary tree, flatten the tree into a "linked list":

  • The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • The "linked list" should be in the same order as a pre-order traversal of the binary tree.

 

Example 1:

Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
        

Example 2:

Input: root = []
Output: []
        

Example 3:

Input: root = [0]
Output: [0]