Convert Sorted List to Binary Search Tree

Given the head of a singly linked list whose values are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced tree is one where the depths of the two subtrees of every node differ by at most one.

30:00

Convert Sorted List to Binary Search Tree
medium
Free written solution
Topics
Companies

Given the head of a singly linked list whose values are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced tree is one where the depths of the two subtrees of every node differ by at most one.

Example 1:
Input: {"head":[-10,-3,0,5,9]}
Output: [0,-3,9,-10,null,5]
Constraints:
  • The number of nodes in head is in the range [0,2×104][0, 2 \times 10^4].

  • −105≤Node.val≤105-10^5 \leq \text{Node.val} \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"head":[-10,-3,0,5,9]}

Count node -10: n = 1. The tree's shape depends only on this count.

0-101-3203549node01234

open calls (innermost first)

none

placed 0 of 5 values

curr / slot being filled
placed node
empty slot
range of the call
Each slot sits under the list cell with the same index: inorder rank equals list position.
Variables
VariableValue
n1
currnull
DepthFunction Call
Stack empty
0/28