题目:
请实现两个函数,分别用来序列化和反序列化二叉树
解答:
1 public class Solution { 2 public int index = -1; 3 4 String Serialize(TreeNode root) { 5 StringBuilder s = new StringBuilder(); 6 7 if(root == null){ 8 s.append("#,"); 9 return s.toString(); 10 } 11 12 s.append(root.val+","); 13 s.append(Serialize(root.left)); 14 s.append(Serialize(root.right)); 15 16 return s.toString(); 17 } 18 19 TreeNode Deserialize(String str) { 20 index++; 21 String[] DLRseq = str.split(","); 22 TreeNode leave = null; 23 if(!DLRseq[index].equals("#")){ 24 leave = new TreeNode(Integer.valueOf(DLRseq[index])); 25 leave.left = Deserialize(str); 26 leave.right = Deserialize(str); 27 } 28 return leave; 29 } 30 }