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

Posted 約束の空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List相关的知识,希望对你有一定的参考价值。

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

递归:

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的主要内容,如果未能解决你的问题,请参考以下文章

426. Convert Binary Search Tree to Sorted Doubly Linked List

426. Convert Binary Search Tree to Sorted Doubly Linked List

426. Convert Binary Search Tree to Sorted Doubly Linked List - Medium

LeetCode(算法)- 426. 将二叉搜索树转化为排序的双向链表

*Leetcode 426 & 剑指 Offer 36. 二叉搜索树与双向链表

*Leetcode 426 & 剑指 Offer 36. 二叉搜索树与双向链表