Trees & BST · Pattern 11 of 12

Tree to list and back: flatten, DLL and sorted list to BST

Pick the traversal order the list must follow and keep a pointer to the last node you linked. Linking each new node to that one rewires the tree in place.

3 variations · 3 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Turn a tree into a linked list (singly or doubly) in place
  • The list must follow preorder or inorder
  • Build a balanced BST from a sorted linked list

The template

Tree to Lists and vice-versa
// binary tree to doubly linked list in inorder: left = prev, right = next
TreeNode head, prev;
TreeNode treeToDLL(TreeNode root) {
    head = prev = null;
    link(root);
    return head;
}
void link(TreeNode node) {
    if (node == null) return;
    link(node.left);
    if (prev == null) head = node;                         // the smallest node starts the list
    else { prev.right = node; node.left = prev; }
    prev = node;
    link(node.right);
}

// flatten to a right-only list in preorder: visit right, left, node and point at the last one
TreeNode last;
void flatten(TreeNode root) {
    last = null;
    reversePreorder(root);
}
void reversePreorder(TreeNode node) {
    if (node == null) return;
    reversePreorder(node.right);
    reversePreorder(node.left);
    node.right = last;                                     // last = the next node in preorder
    node.left = null;
    last = node;
}

The variations

  1. 1Inorder with a prev pointer

    Inorder visits the nodes in list order. Link each node to the previous one in both directions; the first node visited is the head.

  2. 2Preorder into a right-only list

    Walk in reverse preorder (right, left, node) and point each node at the one visited just before it. Or, without recursion, move each left subtree to the right and attach the old right subtree to its rightmost node.

  3. 3From a sorted list back to a tree

    The middle element is the root. Count the nodes, then build the tree in inorder: build the left half, take the current list node as the root, move the list on, build the right half.

Mistakes to avoid

  • Overwriting node.right before you have visited the right subtree: you lose it. Visit first, or save the pointer.
  • Flatten: forgetting to set left = null, so the result is still a tree.
  • Sorted list to BST: finding the middle with slow and fast pointers each time is O(n log n). Building in inorder order while walking the list once is O(n).
Next: Floor, ceil, successor and predecessor in a BST →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.