[Leetcode] Serialization and de-serialization of Serialize and deserialize binary tree two forks

Source: Internet
Author: User

Serialization is the process of converting a data structure or object to a sequence of bits so then it can be stored in A file or memory buffer, or transmitted across a network connection link to being reconstructed later in the same or another Computer environment.

Design a algorithm to serialize and deserialize a binary tree. There is no restriction on what your serialization/deserialization algorithm should work. You just need to ensure, a binary tree can is serialized to a string and this string can is deserialized to the origin AL tree structure.

For example, serialize the following tree

    1   /   2   3     /     4   5

"[1,2,3,null,null,4,5]"as, just the same as how Leetcode OJ serializes a binary tree. You don't necessarily need to follow the this format, so that you are creative and come up with different approaches yourself.

Note: Don't use the class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

This problem allows us to serialize and de-serialize the two-fork tree. Serialization is the conversion of a data structure or object into a sequence of bits that can be stored in a file or memory buffer and then restored through a network connection in the same or another computer environment, and the process of restoration is called de-serialization. Now let's serialize and de-serialize a binary tree and give us an example. This problem has two methods, namely, the recursive method of first order traversal and the non-recursive method of sequence traversal. First of all, the recursive method of first order traversal is very easy to understand, we need to access input and output string flow Istringstream and Ostringstream, for serialization, we start from the root node, if the node exists, the value is stored in the output string stream, Then recursively call the serialization function on the left and right sub-nodes respectively. For de-serialization, we first read the first character, generate a root node, and then recursively call the go-to-serialize function on the left and right child nodes of the root node, see the code below:

//recursionclassCodec { Public:    //encodes a tree to a single string.    stringSerialize (treenode*root) {Ostringstream out; Serialize (Root, out); return  out. STR (); }    //decodes your encoded data to tree.Treenode* Deserialize (stringdata) {Istringstreaminch(data); returnDeserialize (inch); }Private:    voidSerialize (TreeNode *root, Ostringstream & out) {        if(root) { out<< Root->val <<' '; Serialize (Root->left, out); Serialize (Root->right, out); } Else {             out<<"# "; }} TreeNode* Deserialize (Istringstream &inch) {        stringVal; inch>>Val; if(val = ="#")returnnullptr; TreeNode*root =NewTreeNode (Stoi (Val)); Root->left = Deserialize (inch); Root->right = Deserialize (inch); returnRoot; }};

Another method is the non-recursive algorithm of the sequence traversal, this method is slightly more complex, we need to use the queue to do, the essence is the BFS algorithm, it is not difficult to understand, that is, the conventional method of BFS is modified slightly, see the code as follows:

//non-recursionclassCodec { Public:    //encodes a tree to a single string.    stringSerialize (treenode*root) {Ostringstream out; Queue<TreeNode*>Q; if(Root) q.push (root);  while(!Q.empty ()) {TreeNode*t =Q.front (); Q.pop (); if(t) { out<< T->val <<' '; Q.push (t-Left ); Q.push (t-Right ); } Else {                 out<<"# "; }        }        return  out. STR (); }    //decodes your encoded data to tree.Treenode* Deserialize (stringdata) {        if(Data.empty ())returnnullptr; Istringstreaminch(data); Queue<TreeNode*>Q; stringVal; inch>>Val; TreeNode*res =NewTreeNode (Stoi (Val)), *cur =Res;        Q.push (cur);  while(!Q.empty ()) {TreeNode*t =Q.front (); Q.pop (); if(! (inch>> val)) Break; if(val! ="#") {cur=NewTreeNode (Stoi (Val));                Q.push (cur); T->left =cur; }            if(! (inch>> val)) Break; if(val! ="#") {cur=NewTreeNode (Stoi (Val));                Q.push (cur); T->right =cur; }        }        returnRes; }};

Resources:

Https://leetcode.com/discuss/66147/recursive-preorder-python-and-c-o-n

Https://leetcode.com/discuss/66197/solutions-recursive-recursive-time-space-encode-nodetype

Https://leetcode.com/discuss/66212/very-straight-forward-level-traval-using-stringstream-input

Https://leetcode.com/discuss/66243/c-straightforward-preorder-approach

Leetcode all in one topic summary (continuous update ...)

[Leetcode] Serialization and de-serialization of Serialize and deserialize binary tree two forks

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.