Problem Description
Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place. The left pointer of each node represents the predecessor and the right pointer represents the successor. The resulting list should be circular, meaning the predecessor of the smallest element is the largest element and the successor of the largest element is the smallest.
Key Insights
- Use an in-order traversal to process nodes in sorted order.
- Maintain pointers to connect the current node with the previously visited node.
- After traversal, connect the head and tail of the list to make it circular.
- The in-place constraint means no new nodes (or extra data structures for node storage) are created.
Space and Time Complexity
Time Complexity: O(n) – Each node is visited once during the in-order traversal. Space Complexity: O(n) – Due to the recursion stack in the case of an unbalanced tree. For a balanced tree, it can be O(log n).
Solution
We solve the problem using an in-order depth-first search (DFS) traversal to ensure nodes are accessed in sorted order. While traversing:
- Use a helper recursive function to perform the in-order traversal.
- Maintain a reference to the previously processed node (prev) and to the head of the list.
- For each node, connect it with the previous node by setting prev.right to the current node and current node.left to prev.
- Once traversal is complete, connect the head and tail (last node) to make the list circular. The algorithm uses recursion, and the key trick is to update the pointers while unwinding the recursion.