1. 程式人生 > 實用技巧 >[leetcode] 劍指 Offer 專題(四)

[leetcode] 劍指 Offer 專題(四)

《劍指 Offer》專題第四部。

36 二叉搜尋樹和雙向連結串列

題目:劍指 Offer 36. 二叉搜尋樹與雙向連結串列

中序遍歷。時間複雜度 \(O(N)\),空間複雜度 \(O(N)\) .

class Solution {
public:
    vector<Node*> res;
    Node* treeToDoublyList(Node* root) {
        if (root == nullptr) return nullptr;
        inorder(root);
        int len = res.size();
        for (int i=0; i<len; i++)
        {
            int next = (i+1)%len;
            res[i]->right = res[next];
            res[next]->left = res[i];
        }
        return res[0];
    }
    void inorder(Node *p)
    {
        if (p == nullptr) return;
        inorder(p->left);
        res.push_back(p);
        inorder(p->right);
    }
};

37 序列化二叉樹

題目:劍指 Offer 37. 序列化二叉樹.

層次遍歷

層次遍歷實現。More details see:二叉樹的序列化與反序列化

class Codec {
public:
    const string sep = ",";
    const string nil = "null";
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        vector<string> res;
        if (root != nullptr)
        {
            queue<TreeNode*> q;
            q.push(root);
            while (!q.empty())
            {
                auto p = q.front();
                q.pop();
                if (p == nullptr)
                    res.push_back(nil);
                else
                {
                    res.push_back(to_string(p->val));
                    q.push(p->left), q.push(p->right);
                }
            }
        }
        while (!res.empty() && res.back() == nil) res.pop_back();
        string ans = "";
        for (auto &x: res) ans += x + sep;
        if (!ans.empty()) ans.pop_back();
        return "[" + ans + "]";
    }

    inline TreeNode* generateNode(const string &s)
    {
        return s == nil ? nullptr : new TreeNode(stoi(s));
    }

    vector<string> split(string &data, const string &sep)
    {
        size_t l = 0;
        size_t r = data.find(sep, l);
        vector<string> res;
        while (r != string::npos)
        {
            res.push_back(data.substr(l, r - l));
            l = r + sep.length();
            r = data.find(sep, l);
        }
        res.push_back(data.substr(l));
        return res;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) 
    {
        data = data.substr(1, data.length() - 2);
        if (data.length() == 0) return nullptr;

        auto res = split(data, sep);
        int idx = 0, len = res.size();
        auto root = generateNode(res[idx++]);
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty())
        {
            auto p = q.front();
            q.pop();
            if (p == nullptr) continue;
            if (idx < len) p->left = generateNode(res[idx++]), q.push(p->left);
            if (idx < len) p->right = generateNode(res[idx++]), q.push(p->right);
            if (idx >= len) break;
        }
        return root;
    }
};

先序遍歷

遞迴實現。