码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List

时间:2018-08-25 00:48:39      阅读:907      评论:0      收藏:0      [点我收藏+]

标签:void   int   遍历   root   问题   new   null   arc   递归   

看起来很难,但是仔细想一下,实质就是二叉树的中序遍历的问题,中序遍历有递归和非递归(至少两种写法)。

递归:

class Solution {
public:
    Node *prev; //实质是指向最后一个元素的指针
    
    Node* treeToDoublyList(Node* root) {
        if (root==NULL) return NULL;
        Node *dummy=new Node(0,NULL,NULL);
        prev = dummy;
        inorder(root);
        
        prev->right = dummy->right;
        dummy->right->left = prev;
        return dummy->right;
    }
    
    void inorder(Node *root){
        if (root==NULL) return;
        inorder(root->left);
        prev->right = root;
        root->left = prev;
        prev = root;
        inorder(root->right);
    }
};

 

非递归

class Solution {
public:
    Node *prev; //实质是指向最后一个元素的指针
    
    Node* treeToDoublyList(Node* root) {
        if (root==NULL) return NULL;
        
        stack<Node *> s;
        Node *dummy=new Node(0,NULL,NULL);
        Node *p=root, *prev=dummy;
        
        while (!s.empty() || p!=NULL){
            while (p){
                s.push(p);
                p = p->left;
            }
            p = s.top(), s.pop();
                
            prev->right = p;
            p->left = prev;
            prev = p;
                
            p = p->right;
        }
        
        prev->right = dummy->right;
        dummy->right->left = prev;
        
        return dummy->right;
    }
};

 

class Solution {
public:
    Node *prev; //实质是指向最后一个元素的指针
    
    Node* treeToDoublyList(Node* root) {
        if (root==NULL) return NULL;
        
        Node *dummy=new Node(0,NULL,NULL);
        Node *prev=dummy;
        
        stack<Node *> s({root});
        unordered_map<Node *,int> hash;
        while (!s.empty()){
            Node *cur=s.top(); s.pop();
            if (hash[cur]==0){
                ++hash[cur];
                s.push(cur);
                if (cur->left) s.push(cur->left);
            }else{
                prev->right = cur;
                cur->left = prev;
                prev = cur;
                
                if (cur->right) s.push(cur->right);
            }
        }
        
        prev->right = dummy->right;
        dummy->right->left = prev;
        
        return dummy->right;
    }
};

 

Divide and Conquer

 

LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List

标签:void   int   遍历   root   问题   new   null   arc   递归   

原文地址:https://www.cnblogs.com/hankunyan/p/9532493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!