Convert Binary Search Tree to Sorted Doubly Linked List

Medium Linked List

root is the root of a binary search tree, which may be empty: every value in a node's left subtree is smaller than the node's own value, and every value in its right subtree is larger, so no two nodes hold the same value.

Relink the tree's own nodes into a circular doubly linked list in increasing order of value, with no new nodes: change only their left and right. A node's left becomes the node with the next smaller value and its right the node with the next larger value. The list wraps around, so the largest node's right is the smallest node and the smallest node's left is the largest. A tree of one node becomes a node whose left and right are both itself.

Return the node with the smallest value, where the list starts, or null if the tree is empty.

Example 1

Input: root = [12,5,18,2,9,15,21,null,null,7,11]
Output: [2,5,7,9,11,12,15,18,21]
12518291521711

Read in order, the values are 2, 5, 7, 9, 11, 12, 15, 18, 21, so the list starts at 2 and ends at 21. Each node's right is the next value and its left the one before; 21's right is 2, and 2's left is 21.

Example 2

Input: root = [30,10,null,null,20]
Output: [10,20,30]
301020

Example 3

Input: root = []
Output: null
(empty)

Constraints

  • 0 ≤ number of nodes ≤ 10⁵
  • -10⁹ ≤ node.val ≤ 10⁹
  • the tree is a binary search tree, so no two nodes hold the same value

More Linked List

All Linked List problems