LintCode "Binary Tree Serialization"

Here is a BFS solution which is compatible with LeetCode binary tree format.

class Solution {
public:
    /**
     * This method will be invoked first, you should design your own algorithm
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    string serialize(TreeNode *root) {
        string ret;
        queue<TreeNode *> q;
        q.push(root);
        while(!q.empty())
        {
            TreeNode *p = q.front(); q.pop();
            if(!p)
            {
                ret +="# ";
                continue;
            }
            ret += to_string(p->val) + " ";
            q.push(p->left);
            q.push(p->right);
        }
        return ret;
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in
     * "serialize" method.
     */
    TreeNode *deserialize(string str) {
        if (str.empty() || str[0] == '#') return nullptr;

        //    Tokenize
        queue<string> q;
        int i = 0, len = str.length();
        while(i < len)
        {
            int j = i;
            while(j < len && str[j] != ' ') j ++;

            if (j > i)
            {
                string sub = str.substr(i, j - i);
                q.push(sub);
            }

            i = j + 1;
        }

        //
        int hval = atoi(q.front().c_str()); q.pop();
        TreeNode *pRet = new TreeNode(hval);

        queue<TreeNode*> qt;
        qt.push(pRet);
        while(!q.empty())
        {
            TreeNode *p = qt.front(); qt.pop();
            string sval0 = q.front(); q.pop();
            if(sval0 != "#")
            {
                int val0 = atoi(sval0.c_str());
                p->left = new TreeNode(val0);
                qt.push(p->left);
            }
            string sval1 = q.front(); q.pop();
            if(sval1 != "#")
            {
                int val1 = atoi(sval1.c_str());
                p->right = new TreeNode(val1);
                qt.push(p->right);
            }
        }
        return pRet;
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/4849006.html