Topic
Implement two functions, respectively, to serialize and deserialize a binary tree
Solving
What is serialization?
Can be understood as a storage structure
can also be deserialized after serialization
For the tree sequence number, it can be understood as a hierarchical traversal, but also to record the empty nodes, which is to be able to go back
Public class solution {String Serialize (TreeNode root) {if(Root = =NULL)return ""; StringBuilder SB =NewStringBuilder (); Serialize (root, SB);returnSb.tostring (); }voidSerialize (TreeNode root, StringBuilder sb) {if(Root = =NULL) {Sb.append ("#,");return; } sb.append (Root.val); Sb.append (', '); Serialize (Root.left, SB); Serialize (Root.right, SB); }int Index= -1; TreeNode Deserialize (StringStr) {if(Str. Length () = =0)return NULL; string[] STRs =Str. Split (",");returnDeserialize (STRs); } TreeNode Deserialize (string[] STRs) {Index++;if(!strs[Index].equals ("#") {TreeNode root =NewTreeNode (0); Root.val = Integer.parseint (strs[Index]); Root.left = Deserialize (STRs); Root.right = Deserialize (STRs);returnRoot }return NULL; }}
Serialize binary Tree