Skip to main content
Back to problems
#426
Medium Algorithms

Convert binary search tree to sorted doubly linked list

Linked List Stack Tree Depth-First Search Binary Search Tree Binary Tree Doubly-Linked List
65.6% acceptance
Mar 31, 2026
2730
245
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.

Solution

C++
Time O(1)
Space O(1)
LeetCode
solution.cpp
/*
// Definition for a Node.
class Node {
public:
  int val;
  Node* left;
  Node* right;

  Node() {}

  Node(int _val) {
    val = _val;
    left = NULL;
    right = NULL;
  }

  Node(int _val, Node* _left, Node* _right) {
    val = _val;
    left = _left;
    right = _right;
  }
};
*/

class Solution {
public:
  Node* first = nullptr;
  Node* last = nullptr;

  void inorder(Node* node) {
    if (!node) return;
    inorder(node->left);
    if (last) {
      last->right = node;
      node->left = last;
    } else {
      first = node;
    }
    last = node;
    inorder(node->right);
  }

  Node* treeToDoublyList(Node* root) {
    if (!root) return nullptr;
    inorder(root);
    last->right = first;
    first->left = last;
    return first;
  }
};