Topic Description :
Implement two functions to serialize and deserialize the binary tree, respectively.
Thinking Analysis :
Serialized binary tree, which can be traversed by the first order, first root node, then Zuozi, then the right subtree. Note that you want to use StringBuffer, because you can change the string directly, or if the root node is empty, then return "#" directly to the end. This is also the end sign of recursion.
Code :
Import Java.lang.StringBuffer;
Import java.lang.String;
/* public class TreeNode {int val = 0;
TreeNode left = null;
TreeNode right = null;
Public TreeNode (int val) {this.val = val;
} */public class Solution {public int index=-1; String Serialize (TreeNode root) {stringbuffer s =new stringbuffer ();//stringbuffer thread-safe advantage if (root = null
) {S.append ("#,");//Ends Return s.tostring () with "#" and returns a string representation of the data in this sequence.
S.append (root.val+ ",");/note is to put the value of the root node into StringBuffer s.append (Serialize (Root.left));//First left subtree after right subtree, this is the first sequence traversal method
S.append (Serialize (root.right));
return s.tostring ();//Returns a string representation of the data in this sequence.
} TreeNode Deserialize (String str) {index++;
string[] STRR = Str.split (","),//split with "," separated by the array int len = strr.length;
if (index >= len) return null;
TreeNode node = null;
if (!strr[index].equals ("#")) {//array equal equals () is "#" node = new TreeNode (integer.valueof (Strr[index]));
Node.left = Deserialize (str);
Node.right = Deserialize (str);
} return node; }
}