LeetCode 297: Serialize and Deserialize Binary Tree
Posted keepshuatishuati
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 297: Serialize and Deserialize Binary Tree相关的知识,希望对你有一定的参考价值。
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));
以上是关于LeetCode 297: Serialize and Deserialize Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
[Lintcode]7. Serialize and Deserialize Binary Tree/[Leetcode]297. Serialize and Deserialize Binary T
LeetCode 297: Serialize and Deserialize Binary Tree
LeetCode297. Serialize and Deserialize Binary Tree
[leetcode]297. Serialize and Deserialize Binary Tree 序列化与反序列化二叉树