题目链接:http://www.lintcode.com/zh-cn/problem/convert-binary-search-tree-to-doubly-linked-list/
将一个二叉查找树按照中序遍历转换成双向链表。
您在真实的面试中是否遇到过这个题? Yes
样例
给定一个二叉查找树:
4
/ \
2 5
/ \
1 3
返回 1<->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)
return NULL;
DoublyListNode* result=Order(root);
while(result->prev)
result=result->prev;
return result;
}
DoublyListNode* Order(TreeNode * root)
{
if(!root)
return NULL;
DoublyListNode* node=new DoublyListNode(root->val);
if(root->left)
{
DoublyListNode* left=Order(root->left);
while(left->next) left=left->next;
node->prev=left;
left->next=node;
}
if(root->right)
{
DoublyListNode* right=Order(root->right);
while(right->prev) right=right->prev;
node->next=right;
right->prev=node;
}
return node;
}
};