Skip to problem
←

Binary Tree to Doubly Linked List

Hard 0 attempts

Take a binary tree and reshape it, in-place, into a doubly linked list. Reuse the existing node pointers rather than allocating new ones: each node's left pointer becomes the "previous" link of the list, and its right pointer becomes the "next" link. The order of nodes in the resulting list should match the tree's inorder sequence (left, node, right). Return the node that becomes the head of the list.

Function contract

Test inputs are level-order arrays with null for missing children. The function receives tree nodes with val, left, and right properties.

Output: Return the head node of the inorder doubly linked list. Use left as previous and right as next; the head’s left and tail’s right must be null. The runner displays values along right links.

Example 1

Input
root = [10,12,15,25,30,36]
Output
[25,12,30,10,36,15]

Example 2

Input
root = [1]
Output
[1]
Constraints
  • 1 <= Number of nodes <= 10^5
  • -10^5 <= Node.val <= 10^5

Iterative Inorder with Previous Pointer

Visit nodes in inorder, saving each original right child before linking the current node to the preceding node. Reuse left and right as previous and next links.

javascript
function binaryTreeToDll(root) {
  const stack = [];
  let current = root,
    previous = null,
    head = null;
  while (current || stack.length) {
    while (current) {
      stack.push(current);
      current = current.left;
    }
    const node = stack.pop(),
      right = node.right;
    node.left = previous;
    if (previous) previous.right = node;
    else head = node;
    previous = node;
    current = right;
  }
  if (previous) previous.right = null;
  return head;
}

Time: O(n) | Space: O(h) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript