请实现两个函数,分别用来序列化和反序列化二叉树
Java:
1 /* 2 public class TreeNode { 3 int val = 0; 4 TreeNode left = null; 5 TreeNode right = null; 6 7 public TreeNode(int val) { 8 this.val = val; 9 10 } 11 12 } 13 */ 14 public class Solution { 15 private String s ; 16 17 String Serialize(TreeNode root) { 18 if (root == null){ 19 return "#" ; 20 } 21 return root.val + " " + Serialize(root.left) + " " + Serialize(root.right) ; 22 } 23 TreeNode Deserialize(String str) { 24 s = str ; 25 return Deserialize() ; 26 } 27 28 TreeNode Deserialize() { 29 if (s.length() == 0) 30 return null ; 31 int index = s.indexOf(' ') ; 32 String node = index == -1 ? s : s.substring(0,index) ; 33 s = index == -1 ? "" : s.substring(index+1) ; 34 if (node.equals("#")) 35 return null ; 36 int val = Integer.valueOf(node) ; 37 TreeNode t = new TreeNode(val) ; 38 t.left = Deserialize() ; 39 t.right = Deserialize() ; 40 return t ; 41 } 42 }