Skip to problem
←

Flatten Binary Tree to Linked List

Medium 0 attempts

Rearrange the original binary-tree nodes in place into a chain following preorder: visit the root, then its left subtree, then its right subtree.

Set every left pointer to null and use right pointers to connect consecutive nodes. Preserve node values. The final node’s right pointer is null. An empty tree stays empty.

The runner checks the original root after the function finishes; returning a separate tree does not satisfy the task.

Function contract

root is a binary-tree node with val, left, and right properties, or null. Test inputs use level-order arrays with null for missing children; [] becomes null.

Output: Modify the input tree in place. The editor checks the original root after the call and displays its level-order array; return values are ignored.

Example 1

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

Explanation: Preorder visits root, then left subtree, then right subtree: 1 → 2 → 3 → 4 → 5 → 6. Every left pointer becomes null, producing the alternating null entries in the displayed level-order array.

Example 2

Input
root = []
Output
[]
Constraints
  • 0 <= number of nodes <= 2000
  • -100 <= Node.val <= 100

Approach: Morris-like Traversal

For each node with a left child, find the rightmost node of the left subtree. Connect that rightmost node to the current right child. Then move the entire left subtree to the right side and set left to null. Advance to the next right node.

javascript
function flattenBinaryTreeToLinkedList(root) {
  let curr = root;
  while (curr) {
    if (curr.left) {
      let prev = curr.left;
      while (prev.right) prev = prev.right;
      prev.right = curr.right;
      curr.right = curr.left;
      curr.left = null;
    }
    curr = curr.right;
  }
}

Time Complexity: O(n)

Space Complexity: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript