Convert Sorted List to Binary Search Tree

Medium Trees & BST Tree to Lists and vice-versa

Convert Sorted List to Binary Search Tree is a medium trees & bst problem solved with the tree to lists and vice-versa pattern. The best approach, inorder build with a moving pointer, runs in O(n) time and O(log n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from copy into an array up.

Problem

You are given the head of a singly linked list whose values are sorted in strictly increasing order. Build a height-balanced binary search tree that holds exactly these values and return its root.

Height-balanced means that at every node, the heights of the left and right subtrees differ by at most one. Usually more than one tree fits; any of them is accepted. Trees are shown in level order, with null for a missing child.

Examples

Example 1

Input
head = [-7, -2, 0, 4, 9]
Output
[0, -7, 4, null, -2, null, 9]
Why
0 is the middle value, so it becomes the root. The two values before it form the left subtree and the two after it form the right subtree. Every node's two sides differ in height by at most one.

Example 2

Input
head = []
Output
[]
Why
An empty list gives an empty tree.

Example 3

Input
head = [1, 3]
Output
[1, null, 3]
Why
With two values, either one can be the root. Here 1 is the root and 3 is its right child; [3, 1] would also be accepted.

Constraints

  • The list has 0 to 2 * 10^4 nodes.
  • -10^5 <= Node.val <= 10^5
  • The values are in strictly increasing order.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

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

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Copy into an arrayO(n)O(n)
Find the middle with slow and fast pointersO(n log n)O(log n)
Inorder build with a moving pointerO(n)O(log n)

1Copy into an array

TimeO(n)Copying takes one pass, and every value becomes a node exactly once.
SpaceO(n)The array holds all n values; the recursion stack adds only O(log n), because each call halves the range.

Random access is what makes the sorted-array version easy, so first copy the list into an array. Then the middle of any range is one index away: make it the root, build the left half from the values before it and the right half from the values after it.

  1. Walk the list once and put every value into an array.
  2. build(lo, hi): if lo > hi, return null.
  3. mid = lo + (hi - lo) / 2. Make a node with vals[mid].
  4. Its left child is build(lo, mid - 1) and its right child is build(mid + 1, hi). Return the node.
class Solution {
    private int[] vals;

    public TreeNode sortedListToBST(ListNode head) {
        int n = 0;
        for (ListNode p = head; p != null; p = p.next) n++;
        vals = new int[n];
        int i = 0;
        for (ListNode p = head; p != null; p = p.next) vals[i++] = p.val;
        return build(0, n - 1);
    }

    private TreeNode build(int lo, int hi) {
        if (lo > hi) return null;
        int mid = lo + (hi - lo) / 2;
        TreeNode node = new TreeNode(vals[mid]);
        node.left = build(lo, mid - 1);
        node.right = build(mid + 1, hi);
        return node;
    }
}

2Find the middle with slow and fast pointers

TimeO(n log n)Finding a middle walks half of its piece. On each level of the recursion the pieces together cover the list once, and there are about log n levels.
SpaceO(log n)No copy of the values, only the recursion stack, which is about log n deep because every piece is split in half.

Skip the array and work on the list itself. Describe a piece of the list by its first node and the node just after its end (null for the whole list). A slow pointer that moves one step while a fast pointer moves two stops at the middle of the piece. That middle node is the root; the piece before it and the piece after it become the two subtrees.

  1. build(start, end) builds the tree for the nodes from start up to, but not including, end. If start == end, the piece is empty: return null.
  2. Set slow = fast = start. While fast.next != end and fast.next.next != end, move slow one step and fast two steps. Now slow is the middle (the left one when the length is even).
  3. Make a node with slow.val. Its left child is build(start, slow) and its right child is build(slow.next, end).
  4. The answer is build(head, null).
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        return build(head, null);
    }

    // builds the nodes from start up to, but not including, end
    private TreeNode build(ListNode start, ListNode end) {
        if (start == end) return null;
        ListNode slow = start, fast = start;
        while (fast.next != end && fast.next.next != end) {
            slow = slow.next;
            fast = fast.next.next;
        }
        TreeNode node = new TreeNode(slow.val);
        node.left = build(start, slow);
        node.right = build(slow.next, end);
        return node;
    }
}

3Inorder build with a moving pointer

TimeO(n)One pass to count, then each list node is read once as the build moves along the list.
SpaceO(log n)Only the recursion stack, about log n deep, since every range is split in half. The output tree itself is not counted.

An inorder walk of a BST (left subtree, node, right subtree) meets the values in sorted order, which is exactly the order of the list. So count the nodes, then build the tree in inorder over the index range 0 to n - 1. Build the whole left half first; by the time it returns, the list pointer has moved past all of its values and points at the value for the current node. Take it, step the pointer forward, then build the right half. No middle is ever searched for.

  1. Count the nodes: n. Keep a pointer cur at head.
  2. build(lo, hi): if lo > hi, return null. Let mid = lo + (hi - lo) / 2.
  3. left = build(lo, mid - 1). This uses up exactly the values that belong left of mid.
  4. Make a node with cur.val, attach left, and move cur to cur.next.
  5. node.right = build(mid + 1, hi). Return the node. The answer is build(0, n - 1).
class Solution {
    private ListNode cur;

    public TreeNode sortedListToBST(ListNode head) {
        int n = 0;
        for (ListNode p = head; p != null; p = p.next) n++;
        cur = head;
        return build(0, n - 1);
    }

    // builds the tree for list positions lo..hi in inorder
    private TreeNode build(int lo, int hi) {
        if (lo > hi) return null;
        int mid = lo + (hi - lo) / 2;
        TreeNode left = build(lo, mid - 1);
        TreeNode node = new TreeNode(cur.val);
        node.left = left;
        cur = cur.next;
        node.right = build(mid + 1, hi);
        return node;
    }
}

Edge cases to test

  • An empty list (return null)
  • A single node (a tree with one node)
  • Two nodes, where either value may be the root
  • An even length, so there are two middle values to choose from
  • A long list (20000 nodes), where finding the middle again and again costs extra time

Hints

Hint 1

In a sorted array you would take the middle value as the root and build each half the same way. What makes that hard on a linked list?

Hint 2

You can copy the values into an array first, or find the middle of each piece with a slow and a fast pointer. Both work; one costs memory, the other costs time.

Hint 3

An inorder walk of a BST visits the values in sorted order, which is exactly the order of the list. If you know how many nodes each subtree gets, you can build the tree in inorder and just move along the list as you go.

FAQ

What is the best time complexity for Convert Sorted List to Binary Search Tree?

Inorder build with a moving pointer runs in O(n) time and O(log n) extra space. One pass to count, then each list node is read once as the build moves along the list.

Which pattern does Convert Sorted List to Binary Search Tree use?

It is a trees & bst problem that uses the tree to lists and vice-versa pattern. Other problems with the same pattern: Binary Tree to DLL, Flatten Binary Tree to Linked List.

Is there a brute force solution for Convert Sorted List to Binary Search Tree?

Yes. Copy into an array takes O(n) time and O(n) space. Random access is what makes the sorted-array version easy, so first copy the list into an array.

Which edge cases should I test for Convert Sorted List to Binary Search Tree?

An empty list (return null); A single node (a tree with one node); Two nodes, where either value may be the root; An even length, so there are two middle values to choose from; A long list (20000 nodes), where finding the middle again and again costs extra time.