1. Title Description
/ ** Please implement two functions are used to serialize and deserialize binary sequence of binary tree means: to save a binary string of a certain format in accordance with the result of a traversing manner such that the memory set up a binary tree can persist.
Serialization may be based on the first order, in sequence, after, the binary tree traversal sequence is modified, the sequence of the result is a string
representing the blank nodes (#) by some sequences of symbol to! End node represents a value (value!). Deserialized binary tree means: The serialized string str some results obtained traversal order to reconstruct a binary tree. * /
2. preorder traversal
/**先序遍历*/ public class Solution { public int index = -1; /**序列化*/ String Serialize(TreeNode root) { StringBuffer sb = new StringBuffer(); if(root == null){ sb.append("#,"); return sb.toString(); } sb.append(root.val + ",");//根 sb.append(Serialize(root.left));//左 sb.append(Serialize(root.right));//右 return sb.toString(); } /**反序列化*/ TreeNode Deserialize(String str) { index++; String[] strr = str.split(","); TreeNode node = null; if(!strr[index].equals("#")){ node = new TreeNode(Integer.valueOf(strr[index]));//根 node.left = Deserialize(str);//左 node.right = Deserialize(str);//右 } return node; } }
3. traverse the level
// use traversal sequence need not be converted to a simple method for the complete binary tree public class Solution { String the Serialize (the TreeNode the root) { the StringBuilder SB = new new the StringBuilder (); Queue <the TreeNode> Queue = new new the LinkedList <the TreeNode> (); IF (= the root! null ) queue.add (the root); the while (! queue.isEmpty ()) { the TreeNode Node = queue.poll (); IF (! Node = null ) { Queue.offer (node.left); queue.offer (node.right); sb.append(node.val + ","); }else{ sb.append("#" + ","); } } if(sb.length() != 0) sb.deleteCharAt(sb.length()-1); return sb.toString(); } TreeNode Deserialize(String str) { TreeNode head = null; if(str == null || str.length() == 0) return head; String[] nodes = str.split(","); TreeNode[] treeNodes = new TreeNode[nodes.length]; for(int i=0; i<nodes.length; i++){ if(!nodes[i].equals("#")) treeNodes[i] = new TreeNode(Integer.valueOf(nodes[i])); } for(int i=0, j=1; j<treeNodes.length; i++){ if(treeNodes[i] != null){ treeNodes[i].left = treeNodes[j++]; treeNodes[i].right = treeNodes[j++]; } } return treeNodes[0]; } }