/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); dfs(root,sb); return sb.toString(); } void dfs(TreeNode root, StringBuilder sb) { if(root == null) { sb.append(".!"); }else{ sb.append(root.val).append("!"); dfs(root.left,sb); dfs(root.right,sb); } } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { String[] arr = data.split("!"); return decode(arr); } TreeNode decode(String[] arr) { TreeNode node = null; ++index; if(arr[index].equals(".")==false) { node = new TreeNode(Integer.valueOf(arr[index])); node.left = decode(arr); node.right = decode(arr); } return node; } int index = -1; } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));