二叉搜索树——剑指 Offer 36. 二叉搜索树与双向链表

二叉搜索树——剑指 Offer 36. 二叉搜索树与双向链表

题目:

思路:

二叉搜索树,自然就是中序遍历,然后就是构建双向链表就可以了。构建双向链表部分有点忘记,又看了看才明白。然后就干就好了。

代码:

class Solution {
public:
    Node* treeToDoublyList(Node* root) {
        if(root == nullptr) return nullptr;
        Node* head = nullptr, *tail = nullptr;
        //  中序遍历
        build(root, head, tail);
        head->left = tail;
        tail->right = head;
        return head;
    }

    void build(Node* root, Node* &head, Node* &tail){
        if(root){
            // 左
            build(root->left, head, tail);
            // 中
            if(head == nullptr){
                head = tail = root;
            }else{
                tail->right = root;
                root->left = tail;
                tail = root;
            }
            // 右
            build(root->right, head, tail);
        }
    }
};

Rank:

Tips

就是复习一下链表部分,剩下就没啥了。

posted @ 2021-04-22 09:25  Originhhh  阅读(48)  评论(0)    收藏  举报