LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List
Last updated
Last updated
Input: root = [4,2,5,1,3]
Output: [1,2,3,4,5]
Explanation: The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.
Input: root = [2,1,3]
Output: [1,2,3]Input: root = []
Output: []
Explanation: Input is an empty tree. Output is also an empty Linked List.Input: root = [1]
Output: [1]class Solution {
void inorder(Node* cur, Node*& prev, Node*& head) {
if (head == nullptr && cur->left == nullptr) {
head = cur;
}
Node* left = cur->left;
Node* right = cur->right;
if (left != nullptr) {
inorder(left, prev, head);
}
if (prev != nullptr) {
prev->right = cur;
}
cur->left = prev;
prev = cur;
if (right != nullptr) {
inorder(right, prev, head);
}
}
public:
Node* treeToDoublyList(Node* root) {
if (root == nullptr) {
return nullptr;
}
Node* prev = nullptr;
Node* head = nullptr;
inorder(root, prev, head);
prev->right = head;
head->left = prev;
return head;
}
};