Convert a binary search tree to doubly linked list with in-order traversal.
Have you met this question in a real interview?
Yes
Example
Given a binary search tree:
4
/ \
2 5
/ \
1 3
return1<->2<->3<->4<->5
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
* Definition of Doubly-ListNode
* class DoublyListNode {
* public:
* int val;
* DoublyListNode *next, *prev;
* DoublyListNode(int val) {
* this->val = val;
this->prev = this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of tree
* @return: the head of doubly list node
*/
DoublyListNode* bstToDoublyList(TreeNode* root) {
// Write your code here
if (root == nullptr)
return nullptr;
DoublyListNode* left = bstToDoublyList(root->left);
DoublyListNode* right = bstToDoublyList(root->right);
DoublyListNode* mid = new DoublyListNode(root->val);
mid->next = right;
if (right != nullptr)
right->prev = mid;
DoublyListNode head;
head.next = left;
DoublyListNode* cur = &head;
while (cur->next != nullptr)
cur = cur->next;
cur->next = mid;
mid->prev = cur;
return head.next;
}
};