1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 import java.util.*; 11 public class Codec { 12 13 // Encodes a tree to a single string. 14 public String serialize(TreeNode root) { 15 if (root == null) { 16 return null; 17 } 18 StringBuilder result = new StringBuilder(); 19 serl(root, result); 20 return result.toString(); 21 } 22 23 private void serl(TreeNode root, StringBuilder result) { 24 if (root == null) { 25 result.append("# "); 26 return; 27 } 28 result.append(root.val + " "); 29 serl(root.left, result); 30 serl(root.right, result); 31 } 32 33 // Decodes your encoded data to tree. 34 public TreeNode deserialize(String data) { 35 if (data == null) { 36 return null; 37 } 38 StringTokenizer st = new StringTokenizer(data, " "); 39 return derl(st); 40 } 41 private TreeNode derl(StringTokenizer st) { 42 if (st == null) { 43 return null; 44 } 45 46 if (!st.hasMoreTokens()) { 47 return null; 48 } 49 String current = st.nextToken(); 50 if (current.equals("#")) { 51 return null; 52 } 53 54 TreeNode root = new TreeNode(Integer.parseInt(current)); 55 root.left = derl(st); 56 root.right = derl(st); 57 return root; 58 } 59 } 60 61 // Your Codec object will be instantiated and called as such: 62 // Codec codec = new Codec(); 63 // codec.deserialize(codec.serialize(root));