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;
    }
};

时间: 2024-10-25 06:54:07

LintCode "Binary Tree Serialization"的相关文章

lintcode 中等题:binary tree serialization 二叉树的序列化和反序列化

题目 二叉树的序列化和反序列化 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构. 样例 给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构: 3 / 9 20 / 15 7 我们的数据是进行BFS遍历得到的.当你测试结果wrong answer时,你可以作为输

Lintcode7 Binary Tree Serialization solution 题解

[题目描述] Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'. 设计一个算法,并编写代码来序列化

Binary Tree Serialization

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'. There is no limit of ho

LintCode: Binary Tree Preorder Traversal

C++,递归 1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int val) { 8 * this->val = val; 9 * this->left = this->right = NULL; 10 * } 11 * } 12 */ 13 14 class Solution { 15 pub

LintCode: Binary Tree Postorder Traversal

C++,递归 1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int val) { 8 * this->val = val; 9 * this->left = this->right = NULL; 10 * } 11 * } 12 */ 13 class Solution { 14 /** 15

[Lintcode]Binary Tree Zigzag Level Order Traversal

Binary Tree Zigzag Level Order Traversal Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). Example Given binary tree {3,9,20,#,#,1

LintCode Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return [ [3], [9,20], [15,7] ] For the problem given I decided to use BFS, howe

[lintcode] Binary Tree Inorder Traversal

Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' values. Example Given binary tree {1,#,2,3}, 1 2 / 3 return [1,3,2]. SOLUTION 1: 递归方法,具体代码可以参照preorder traversal,这里就不赘述了. SOLUTION 2: 分治法,Divide & conquer,其

[LintCode] Binary Tree Vertical Order Traversal

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. Have you met this question in a real inter