【LeetCode刷题(困难程度)】剑指 Offer 37. 序列化二叉树

请实现两个函数,分别用来序列化和反序列化二叉树。

示例:

你可以将以下二叉树:
在这里插入图片描述
思路:序列化就是说根据某一种遍历算法把树的节点值存储起来,反序列化就是能够根据此存储的值重建二叉树,从官方题解这里给出的示例可以看出,用的是层次遍历,那我们也用层次遍历吧。

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            TreeNode* tmp = q.front();
            q.pop();
            if (tmp) {
                out<<tmp->val<<" ";
                q.push(tmp->left);
                q.push(tmp->right);
            } else {
                out<<"null ";
            }
        }
        return out.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream input(data);
        string val;
        vector<TreeNode*> vec;
        while (input >> val) {
            if (val == "null") {
                vec.push_back(NULL);
            } else {
                vec.push_back(new TreeNode(stoi(val)));
            }
        }
        int j = 1;  // i每往后移动一位,j移动两位,j始终是当前i的左子下标
        for (int i = 0; j < vec.size(); ++i) // 肯定是j先到达边界,所以这里判断j < vec.size()
        {  
            if (vec[i] == NULL) 
                continue;     // vec[i]为null时跳过。
            if (j < vec.size()) 
                vec[i]->left = vec[j++];   // 当前j位置为i的左子树
            if (j < vec.size()) 
                vec[i]->right = vec[j++];  // 当前j位置为i的右子树
        }
        return vec[0];
 
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

直观一点的实现方法,但是时间和空间比上面那种高很多。(或许重建时采用数组索引快一些吧)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string ret = "";
        queue<TreeNode*> st;
        st.push(root);

        while(!st.empty())
        {
            TreeNode* front = st.front();
            st.pop();
            if(front == NULL)
            {
                ret +="null ";
            }
            else
            {
                ret = ret + to_string(front->val)+" ";
                st.push(front->left);
                st.push(front->right);
            }
        }
        return ret;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        TreeNode* ret = nullptr;
        queue<TreeNode*> q;
        istringstream input(data);
        string s;   
        input>>s;

        if(s!="null")
        {
            ret = new TreeNode(stoi(s));
            q.push(ret);
            while(!q.empty())
            {
                TreeNode* front = q.front();
                q.pop();
                string left, right;
                input>>left>>right;

                if(left!="null")
                {
                    front->left = new TreeNode(stoi(left));
                    q.push(front->left);
                }
                if(right!="null")
                {
                    front->right = new TreeNode(stoi(right));
                    q.push(front->right);
                }
            }
        }
        return ret;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

猜你喜欢

转载自blog.csdn.net/qq_33197518/article/details/108968703