Topic:
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:do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Ideas:
Serialization: Sequence traversal of a binary tree.
Deserialization: Sequence constructs a binary tree.
/** Definition for a binary tree node. * Function TreeNode (val) {* This.val = val; * This.left = This.right = Null * } *//** * encodes a tree to a single string. * * @param {TreeNode} root * @return {string}*/varSerialize =function(root) {if(root==NULL){ return []; } varqueue=[],res=[]; Queue.push (root); while(queue.length!=0){ varp=Queue.unshift (); Res.push (P.val); if(p!=NULL) {Queue.push (p.left.val); Queue.push (P.right.val); } } returnRes;};/** * decodes your encoded data to tree. * * @param {string} data * @return {TreeNode}*/varDeserialize =function(data) {if(data.length==0){ return NULL; } varroot=NewTreeNode (Data[0]), queue=[],res,loc=1; Queue.push (root); while(queue.length!=0){ varp=Queue.unshift (); varCount=0; while(count<2) {Count++; varChild=NULL; if(data[loc]==NULL){ if(loc%2!=0) { child=NewTreeNode (Data[loc]); P.left=Child ; }Else{ Child=NewTreeNode (Data[loc]); P.right=Child ; } queue.push (child); }Else{ if(loc%2!=0) {P.left=NULL; }Else{ Child=NewTreeNode (Data[loc]); P.right=NULL; } } } } returnroot;};/** * Your functions'll be called as such: * Deserialize (serialize (root));*/
"Tree" Serialize and deserialize Binary tree