
Problem
Solution
Submissions
Convert Binary Search Tree to Sorted Doubly Linked List
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a Python function to convert a Binary Search Tree (BST) to a sorted Circular Doubly Linked List. The transformation should be done in-place, with the BST nodes becoming nodes in the doubly linked list. The left pointer of the BST should become the previous pointer in the linked list, and the right pointer should become the next pointer. The linked list should be circular, meaning the last node's next pointer should point to the first node, and the first node's previous pointer should point to the last node. Return the head of the resulting sorted doubly linked list.
Example 1
- Input:
- Output: 1 ⟷ 2 ⟷ 3 ⟷ 4 ⟷ 5 ⟷ (back to 1)
- Explanation:
- The BST is converted to a sorted circular doubly linked list with the following connections:
- - 1's prev points to 5, 1's next points to 2
- - 2's prev points to 1, 2's next points to 3
- - 3's prev points to 2, 3's next points to 4
- - 4's prev points to 3, 4's next points to 5
- - 5's prev points to 4, 5's next points to 1
Example 2
- Input:
- Output: 1 ⟷ 2 ⟷ 3 ⟷ (back to 1)
- Explanation:
- The BST is converted to a sorted circular doubly linked list with the following connections:
- - 1's prev points to 3, 1's next points to 2
- - 2's prev points to 1, 2's next points to 3
- - 3's prev points to 2, 3's next points to 1
Constraints
- The number of nodes in the tree is in the range [0, 2000]
- -1000 <= Node.val <= 1000
- All values in the tree are unique
- Time Complexity: O(n) where n is the number of nodes
- Space Complexity: O(h) where h is the height of the tree
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Consider using an in-order traversal to visit the BST nodes in ascending order
- Maintain a reference to the previously visited node during traversal
- Update the links between current and previous nodes during traversal
- After traversal, connect the first and last nodes to make the list circular
- Keep track of the head (first node) to return at the end