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 public class Codec { 11 12 // Encodes a tree to a single string. 13 public String serialize(TreeNode root) { 14 if (root == null) { 15 return null; 16 } 17 StringBuilder result = new StringBuilder(); 18 dfs(root, result); 19 return result.toString(); 20 } 21 22 private void dfs(TreeNode root, StringBuilder sb) { 23 if (root == null) { 24 sb.append(" ").append("#"); 25 return; 26 } 27 sb.append(root.val).append("#"); 28 dfs(root.left, sb); 29 dfs(root.right, sb); 30 } 31 32 // Decodes your encoded data to tree. 33 public TreeNode deserialize(String data) { 34 if (data == null) { 35 return null; 36 } 37 LinkedList<String> nodeList = new LinkedList<>(); 38 nodeList.addAll(Arrays.asList(data.split("#"))); 39 return getTree(nodeList); 40 } 41 42 private TreeNode getTree(LinkedList<String> nodeList) { 43 String current = nodeList.poll(); 44 if (current == null || current.equals(" ")) { 45 return null; 46 } 47 48 TreeNode root = new TreeNode(Integer.valueOf(current)); 49 root.left = getTree(nodeList); 50 root.right = getTree(nodeList); 51 return root; 52 } 53 } 54 55 // Your Codec object will be instantiated and called as such: 56 // Codec codec = new Codec(); 57 // codec.deserialize(codec.serialize(root));
时间: 2024-10-06 18:28:24