Convert Binary Search Tree to Sorted Doubly Linked List - Problem
Transform a Binary Search Tree (BST) into a sorted circular doubly-linked list in place! ๐Ÿ”„

Imagine you have a BST where nodes are connected by left and right pointers. Your mission is to rewire these connections so that:

โ€ข The left pointer becomes the predecessor (previous node)
โ€ข The right pointer becomes the successor (next node)
โ€ข The list is circular: first node's left points to last, last node's right points to first
โ€ข The transformation must be done in place (no new nodes)

Since it's a BST, an in-order traversal gives us the sorted sequence. Your goal is to return the pointer to the smallest element (the head of our circular list).

Key Challenge: Maintain the sorted order while converting the tree structure into a doubly-linked list structure.

Input & Output

example_1.py โ€” Basic BST
$ Input: root = [4,2,5,1,3]
โ€บ Output: Circular doubly linked list: 1<->2<->3<->4<->5<->1...
๐Ÿ’ก Note: The BST is converted to a sorted circular doubly linked list. Node 1 (smallest) is returned as head. Each node's left points to predecessor, right to successor.
example_2.py โ€” Single Node
$ Input: root = [2]
โ€บ Output: Circular doubly linked list: 2<->2 (points to itself)
๐Ÿ’ก Note: Single node case: the node's left and right pointers both point to itself, forming a circular list of size 1.
example_3.py โ€” Empty Tree
$ Input: root = []
โ€บ Output: null
๐Ÿ’ก Note: Empty tree returns null as there are no nodes to form a doubly linked list.

Visualization

Tap to expand
BST โ†’ Circular Doubly Linked ListBefore: Binary Search Tree42513TransformAfter: Circular Doubly Linked List12345CircularConnectionsIn-Order Traversal Sequence: 1 โ†’ 2 โ†’ 3 โ†’ 4 โ†’ 512345
Understanding the Visualization
1
Traverse In-Order
Visit nodes in sorted order: 1, 2, 3, 4, 5
2
Link as We Go
Connect each node to the previous one immediately
3
Complete the Circle
Connect first and last nodes to make it circular
Key Takeaway
๐ŸŽฏ Key Insight: In-order traversal of a BST naturally gives us nodes in sorted order, allowing us to build the doubly-linked list connections incrementally without extra storage!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

O(n) for in-order traversal + O(n) for reconstructing links = O(n) total

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

O(n) for storing all nodes in array + O(h) for recursion stack where h is tree height

n
2n
โšก Linearithmic Space

Constraints

  • The number of nodes in the tree is in the range [0, 2000]
  • -1000 โ‰ค Node.val โ‰ค 1000
  • All the values of the tree are unique
  • The tree is guaranteed to be a valid Binary Search Tree
Asked in
Google 45 Facebook 38 Microsoft 32 Amazon 28
89.4K Views
Medium-High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen