← Questions

Convert a BST to a sorted circular doubly linked list

0
AppleMetaCodingLast asked Jun 2026

A coding interview question asked in Apple's coding round and at Meta, last asked Jun 2026. It tests trees, linked lists and in-order traversal.

Rearrange a binary search tree, in place, into a circular doubly linked list in sorted order. Reuse each node's left pointer as "previous" and right as "next". The last node's next is the first node and the first node's previous is the last. Return the smallest node.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • tree_to_list(root: Node | None) -> Node | None — returns the head (smallest value), or None for an empty tree. Create no new nodes.

Example

        4
       / \
      2   5
     / \
    1   3

tree_to_list(root)  ->  head = 1
next:  1 -> 2 -> 3 -> 4 -> 5 -> 1
prev:  1 -> 5 -> 4 -> 3 -> 2 -> 1

A single node becomes a list whose next and previous both point to itself.

Constraints

  • Up to 2000 nodes; values are distinct.
  • O(1) extra space beyond the recursion stack (or none, for a follow-up).

Clarifying questions

  • Should the list be circular, or end in None?
  • Must it be in place, with no new nodes?
  • Can the tree be very deep (a sorted insertion order)?
  • Return the head, or any node?

What a strong answer covers

  • In-order traversal keeping first and prev: link prev.right = node, node.left = prev, then advance; after the traversal, connect last and first in both directions.
  • O(n) time, O(h) stack for the recursive version.
  • An iterative in-order with an explicit stack for skewed trees; Morris traversal for O(1) extra space.
  • Edge cases: empty tree, one node, a tree that is a single chain.
  • A checker in tests that walks next and prev n steps and checks sorted order and the wraparound.

Follow-ups

  • Do it with O(1) extra space.
  • Convert the sorted circular list back into a balanced BST.
  • Merge two BSTs into one sorted list using this conversion.

Where it's asked

  • Apple · Coding · Last asked Jun 2026
  • Meta · Technical phone screen · Last asked Sep 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

trees · linked lists · in-order traversal

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding