http://www.lintcode.com/zh-cn/problem/convert-binary-search-tree-to-doubly-linked-list/#
递归做法:
- 分别将BST的左、右子树转换成双向链表
- new出一个链表节点,值等于BST根节点的值
- 由于是BST,所以new出的节点应该位于链表的中间,所以分别连接左、右子树转换成的链表。这一步中须要找到左链表的尾节点。
对于一些细节处理,要加上必要的判空语句(链表节点为空时,不能访问它)
/**
* 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) {
if (!root) return NULL;
DoublyListNode *left = bstToDoublyList(root->left);
DoublyListNode *right = bstToDoublyList(root->right);
DoublyListNode *left_tail = left;
while (left_tail && left_tail->next) left_tail = left_tail->next;
DoublyListNode *cur = new DoublyListNode(root->val);
cur->prev = left_tail;
if (left_tail) left_tail->next = cur;
cur->next = right;
if (right) right->prev = cur;
if (left) return left;
else return cur;
}
};