首页 > 其他 > 详细

LeetCode 297: Serialize and Deserialize Binary Tree

时间:2017-07-23 09:24:00      阅读:282      评论:0      收藏:0      [点我收藏+]
 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

原文:http://www.cnblogs.com/shuashuashua/p/7223522.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!