您的位置:首页 > Web前端

LintCode-剑指Offer-(378)将二叉查找树转换成双链表

2015-11-29 14:18 441 查看
class Solution {
public:
/**
* @param root: The root of tree
* @return: the head of doubly list node
*/
DoublyListNode* bstToDoublyList(TreeNode* root) {
// Write your code here

return getDouble(root);

}

DoublyListNode* getDouble(TreeNode* node){
DoublyListNode* root=NULL;
DoublyListNode* prenode = NULL;
DoublyListNode* curnode = NULL;
stack<TreeNode*> rightnodestack;
TreeNode* tmp = node;
while (tmp!=NULL){
rightnodestack.push(tmp);
tmp = tmp->left;
}
while (rightnodestack.empty()==false){
if (root == NULL){
root = new DoublyListNode(rightnodestack.top()->val);
root->prev = NULL;
prenode = root;
}
else{
curnode = new DoublyListNode(rightnodestack.top()->val);
curnode->prev = prenode;
prenode->next = curnode;
prenode = curnode;
}
//cout<<rightnodestack.top()->val<<endl;
TreeNode* tmp = rightnodestack.top()->right;
rightnodestack.pop();
while (tmp!=NULL){
rightnodestack.push(tmp);
tmp = tmp->left;
}
}
return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: