LeetCode solutions

114. Flatten Binary Tree to Linked List

My accepted JavaScript solution to LeetCode problem 114, Flatten Binary Tree to Linked List, running in 0ms.

  • Difficulty: Medium
  • JavaScript
  • Runtime 0ms
  • Memory 55.2MB

Read the problem on LeetCode View on GitHub

JavaScript

Accepted on LeetCode — runtime 0ms, memory 55.2MB, accepted 2025-12-24.

javascript
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function(root) {
    let curr = root;
    
    while (curr) {
        if (curr.left) {
            // Find rightmost node in left subtree
            let prev = curr.left;
            while (prev.right) {
                prev = prev.right;
            }
            
            // Connect rightmost to current's right subtree
            prev.right = curr.right;
            
            // Move left subtree to right
            curr.right = curr.left;
            curr.left = null;
        }
        
        curr = curr.right;
    }
};

Source