首页 > 代码库 > LeetCode 297: Serialize and Deserialize Binary Tree
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 =http://www.mamicode.com/= 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。