Convert Binary Search Tree to Sorted Doubly Linked List Problem
Description
LeetCode Problem 426.
Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.
You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.
We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.
Example 1:

Input: root = [4,2,5,1,3]

Output: [1,2,3,4,5]
Explanation: The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.

Example 2:
Input: root = [2,1,3]
Output: [1,2,3]
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.
Solution
Approach: In-Order Traversal
An in-order traversal (left subtree, node, right subtree) visits the nodes of a BST in increasing order. That is exactly the order of the list we want. So we only need to link each node to the one visited just before it.
Keep two pointers during the traversal:
prev: the last node visited, which is the current end of the list built so far;head: the first node visited, which is the smallest node.
When the traversal visits node:
- if
previs empty,nodeis the smallest node, so it becomeshead; - otherwise link the two:
prev.right = nodeandnode.left = prev.
Then node becomes prev. After the traversal, prev is the largest node. Close the circle with prev.right = head and head.left = prev, and return head.
Changing the pointers while we traverse is safe. By the time node is visited, its left subtree is finished, so overwriting node.left loses nothing. prev.right is only overwritten after prev's right subtree is finished too. The case to handle separately is the empty tree: return null before touching prev.
Complexity: O(n) time. O(h) extra space for the recursion, where h is the height of the tree (up to n for a skewed tree).
class Solution:
def treeToDoublyList(self, root: 'Optional[Node]') -> 'Optional[Node]':
if root is None:
return None
head = prev = None # the smallest node, and the last node linked so far
def inorder(node):
nonlocal head, prev
if node is None:
return
inorder(node.left)
if prev is None:
head = node # the first node visited is the smallest
else:
prev.right = node
node.left = prev
prev = node
inorder(node.right)
inorder(root)
prev.right = head # close the circle: prev is now the largest node
head.left = prev
return head