二叉树的序列化和反序列化

来源:互联网 发布:手机淘宝怎么换用户 编辑:程序博客网 时间:2024/04/29 02:20

        该题首先用先序遍历的思路把树转换(序列化)为字符串,这样在恢复的时候就可以根据字符串先序遍历的特点进行恢复(反序列化)。

   string int2str(int intsrc){        stringstream ss;        ss << intsrc;        return ss.str();    }//序列化代码,先序遍历的顺序进行序列化        string serialize(TreeNode *root) {        // write your code here        string sec;        if(root == nullptr){            sec += "# ";        }else{            sec += int2str(root -> val);            sec += " ";            sec += serialize(root -> left);            sec += serialize(root -> right);        }        return sec;    }    /**     * 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.     *///找到序列中下一个树的节点字符串         int pos = 0;    string nextString(string src){        string result;        if(pos < src.length()){            if(src[pos] == ' '){                pos++;            }            while(src[pos] != ' '){                result += src[pos];                pos++;            }            return result;        }    }        int str2int(string strsrc){        return atoi(strsrc.c_str());    }//反序列化,根据字串先序遍历的特点         TreeNode *deserialize(string data) {        // write your code here        string cur = nextString(data);        if(cur == "#"){            return nullptr;        }else{            TreeNode *root = new TreeNode(str2int(cur));            root -> left = deserialize(data);            root -> right = deserialize(data);            return root;        }    }

0 0
原创粉丝点击