[Lintcode] Binary Tree Serialization

Source: Internet
Author: User
Tags tree serialization lintcode

Design a algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file was called ' serialization ' and reading back from the file to reconstruct the exact same binary T REE is ' deserialization '.

There is no limit the how do you deserialize or serialize a binary tree and you have need to make sure can serialize a binary Tree to a string and deserialize this string to the original structure.

Example

An example of testdata:binary tree {3,9,20,#,#,15,7} , denote the following structure:

  3 / 9  20  /   15   7

Our data serialization use BFS traversal. This was just for when you got wrong answer and want to debug the input.

You can use the other method to do Serializaiton and deserialization.

Basic ideas:

Use the queue hierarchy to traverse the whole tree. For each outbound node, if it is an empty node, add the tag ' # ' after the string. If it is not an empty node, add its Val to the string (if the string is currently ending with a non-empty node, we add a ' _ ' interval) and then join the two children of that node (the empty node is also queued once).

/** Definition of TreeNode: * Class TreeNode {* Public: * int val; * TreeNode *left, *right; * TreeNode (i NT val) {* This->val = val; * This->left = This->right = NULL; *} *}*/classSolution {Private:    Static Const CharNullnode ='#'; Static Const CharNodespliter ='_'; InlinestringINT2STR (intval)        {StringStream strstream; Strstream<<Val; returnStrstream.str (); } InlineintStr2Int (stringstr) {        returnatoi (Str.c_str ()); } InlinevoidEncodestring&AMP;STR, TreeNode *node) {        if(node = =NULL) {STR+=Nullnode; return; }                if(str = =""|| Str.back () = =nullnode) Str+ = Int2str (node->val); ElseStr+ = Nodespliter + int2str (node->val); } Vector<string> Splitstr (string&str) {Vector<string>result; if(str = ="")returnresult; intStart =0, end =0, n =str.size ();  while(true){             while(Start < n && Str[start] = = nodespliter) + +start; if(Start >= N) Break; End= Start +1; if(Str[start]! =Nullnode) {                 while(End < n && str[end]! = Nullnode && str[end]! =nodespliter)++end; } result.push_back (Str.substr (Start, End-start)); Start=end; }        returnresult; }     Public:    /** * This method is invoked first, should design your own algorithm * to serialize a binary tree whic     h denote by a root node to a string which * can is easily deserialized by your own "deserialize" method later. */    stringSerialize (TreeNode *root) {       if(Root = NULL)return ""; stringEncodedstr =""; Queue<TreeNode*>Nodequeue;              Nodequeue.push (root);  while(!Nodequeue.empty ()) {TreeNode*cur =Nodequeue.front ();            Nodequeue.pop ();            Encode (encodedstr, cur); if(cur! =NULL) {Nodequeue.push (cur-Left ); Nodequeue.push (cur-Right ); }       }              returnEncodedstr; }    /** * This method would be invoked second, the argument data are what exactly * you serialized at method "Serializ E ", that means the data was not given by * system, it's given by your own Serialize method. The. The format of data is * designed by yourself, and deserialize it as you serialize it in * "Serialize" met     Hod. */TreeNode*deserialize (stringdata) {Vector<string> splitres =splitstr (data); if(splitres.size () = =0)returnNULL; TreeNode*root =NewTreeNode (Str2Int (splitres[0])); Queue<TreeNode*>Nodequeue;                Nodequeue.push (root);  for(inti =1; i < splitres.size (); i+=2){            if(Nodequeue.empty ())returnRoot; TreeNode*curnode =Nodequeue.front ();            Nodequeue.pop (); //Left son            if(splitres[i][0] ==Nullnode) {Curnode->left =NULL; }Else{Curnode->left =NewTreeNode (Str2Int (splitres[i)); Nodequeue.push (Curnode-Left ); }            //Right son            if(Splitres[i +1][0] ==Nullnode) {Curnode->right =NULL; }Else{Curnode->right =NewTreeNode (Str2Int (splitres[i +1])); Nodequeue.push (Curnode-Right ); }        }                returnRoot; }};

[Lintcode] Binary Tree Serialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.