A music player keeps a playlist sorted by track number in a binary search tree, so inserts are fast. For the "repeat all" mode it wants to walk the tracks forwards and backwards forever, wrapping from the last track to the first. Instead of copying the tree, it reuses the same node objects as a circular doubly linked list.
Each node is a plain object { value, left, right } with distinct number values: smaller values in the left subtree, larger values in the right. Write treeToCircularList(root):
Rearrange the existing nodes so that, for every node, right points to the node with the next larger value and left points to the node with the next smaller value.
The list is circular: the largest node's right is the smallest node, and the smallest node's left is the largest node.
Return the smallest node (the head of the list), or null for an empty tree (root === null).
Rules:
Work in place: do not create nodes, copy nodes or change any value. Every node of the tree must appear exactly once in the list.
A single node becomes a list of one: its left and right both point to itself.
If root is neither null nor an object, throw a TypeError.
Trees can be 200,000 levels deep (a sorted insert sequence makes a chain). Recursion one call per level will overflow the stack, so walk the tree iteratively. Aim for O(n) time and O(h) extra space, where h is the height.
// 4// / \// 2 5// / \// 1 3const head = treeToCircularList(root);head.value; // 1head.right.value; // 2head.left.value; // 5 (wraps to the largest)head.left.right === head; // true// Walking right from head: 1, 2, 3, 4, 5, 1, 2, ...
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.