Skip to content

0109. Convert Sorted List to Binary Search Tree

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1:

img

Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [0]
Output: [0]

Example 4:

Input: head = [1,3]
Output: [3,1]

Constraints:

  • The number of nodes in head is in the range [0, 2 * 104].
  • -10^5 <= Node.val <= 10^5

Analysis

To build a bst from a sorted array, we can do so by recursively finding the middle of the array to generate the tree. However, we need extra time to find the middle of a LinkedList (use a fast-slow pointer requires O(n))

We can definitely use fast-slow pointer to find the mid in each iteration and the pseudo code would like

  sort(node):
        set mid = find_min_for_head
    set root->value = mid->value
    set root -> left = sort(node)
    set root -> right = sort(node)

Using this way, we can generate the balanced search tree.

  • Time: O(n)
  • Space: O(n) for call stack

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    TreeNode* dfs(ListNode* head, ListNode* tail) {
        if (head == tail) return nullptr;
        ListNode* mid = head, *curr = head;
        while (curr != tail && curr -> next != tail) {
            mid = mid -> next;
            curr = curr -> next -> next;
        }
        TreeNode* root = new TreeNode(mid -> val);
        root -> left = dfs(head, mid);
        root -> right = dfs(mid -> next, tail);
        return root;
    }

    TreeNode* sortedListToBST(ListNode* head) {
        return dfs(head, nullptr);
    }
};

Last update: April 1, 2022