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.
Example:
Serialize the following tree: 1 / 2 3 / 4 "[1,2,3,null,null,4,5]"
Clarification:the above format is the same as how leetcode 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:
Code:
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classCodec { One A //encodes a tree to a single string. - PublicString serialize (TreeNode root) { -StringBuilder SB =NewStringBuilder (); the buildstring (root, SB); - returnsb.tostring (); - } - + Private voidbuildstring (TreeNode root, StringBuilder sb) { - if(Root = =NULL){ + //Splitter: "," ASb.append ("#"). Append (","); at}Else{ - //I Use pre-order Traversal:root. -Sb.append (Root.val). Append (","); - buildstring (Root.left, SB); - buildstring (Root.right, SB); - } in } - to //decodes your encoded data to tree. + PublicTreeNode Deserialize (String data) { - if(Data = =NULL)return NULL; theString[]stringarr = Data.split (","); *queue<string> queue =NewLinkedlist<>(); $ //put each item of Stringarr into queuePanax Notoginseng collections.addall (queue, Stringarr); - returnbuildtree (queue); the } + A PrivateTreeNode Buildtree (queue<string>queue) { the if(Queue.isempty ())return NULL; +String Curstr =Queue.poll (); - if(Curstr.equals ("#"))return NULL; $ //To match serialize traversal order, I use pre-order Traversal:root, left, right $TreeNode root =NewTreeNode (Integer.parseint (CURSTR)); -Root.left =buildtree (queue); -Root.right =buildtree (queue); the returnRoot; - } Wuyi } the - //Your Codec object would be instantiated and called as such: Wu //Codec Codec = new Codec (); - //Codec.deserialize (Codec.serialize (root));
[leetcode]297. Serialize and deserialize binary tree serialization and deserialization of binary trees