[Java]LeetCode297. 二叉树的序列化与反序列化 | Serialize and Deserialize Binary Tree

ぃ、小莉子 提交于 2021-02-18 00:43:43

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10693873.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Example: 

You may serialize the following tree:

    1
   / \
  2   3
     / \
    4   5

as "[1,2,3,null,null,4,5]"

Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.


序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。

请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。

示例: 

你可以将以下二叉树:

    1
   / \
  2   3
     / \
    4   5

序列化为 "[1,2,3,null,null,4,5]"

提示: 这与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。

说明: 不要使用类的成员 / 全局 / 静态变量来存储状态,你的序列化和反序列化算法应该是无状态的。


0.5ms

 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     private TreeNode n;
13     
14     // Encodes a tree to a single string.
15     public String serialize(TreeNode root) {
16         this.n = root;
17         return null;
18     }
19 
20     // Decodes your encoded data to tree.
21     public TreeNode deserialize(String data) {
22         return n;
23     }
24 }
25 
26 // Your Codec object will be instantiated and called as such:
27 // Codec codec = new Codec();
28 // codec.deserialize(codec.serialize(root));

1ms

 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     List<Integer> lstNums = new ArrayList<>();
12   int ix = 0;
13 
14   // Encodes a tree to a single string.
15   public List<Integer> serialize(TreeNode root){
16     if(root == null){
17       lstNums.add(null);
18       return lstNums;
19     }
20 
21     lstNums.add(root.val);
22     serialize(root.left);
23     serialize(root.right);
24 
25     return lstNums;
26   }
27 
28   // Decodes your encoded data to tree.
29   public TreeNode deserialize(List<Integer> data){
30     if(ix >= data.size() || data.get(ix) == null){
31       ix++;
32       return null;
33     }
34 
35     TreeNode t = new TreeNode(data.get(ix));
36     ix++;
37 
38     t.left = deserialize(data);
39     t.right = deserialize(data);
40 
41     return t;
42   }
43 }
44 
45 // Your Codec object will be instantiated and called as such:
46 // Codec codec = new Codec();
47 // codec.deserialize(codec.serialize(root));

2ms

 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         StringBuilder sb = new StringBuilder();
15         traverse(root , sb);
16         sb.deleteCharAt(sb.length() - 1);
17         return sb.toString();
18     }
19 
20     // Decodes your encoded data to tree.
21     public TreeNode deserialize(String data) {
22         int[] index = new int[1];
23         return buildTree(data , index);
24     }
25     
26     public void traverse(TreeNode root , StringBuilder sb) {
27         if (root == null) {
28             sb.append("#,");
29             return;
30         }
31         Integer val = root.val;
32         sb.append(val.toString());
33         sb.append(',');
34         traverse(root.left , sb);
35         traverse(root.right , sb);
36     }
37     
38     public TreeNode buildTree (String data , int[] index) {
39         if (index[0] >= data.length()) {
40             return null;
41         } else if (data.charAt(index[0]) == '#') {
42             index[0] += 2;
43             return null;
44         }
45         TreeNode node = new TreeNode(getValue(data , index[0]));
46         while(data.charAt(index[0]) != ',') {
47             index[0] ++;
48         }
49         index[0]++;
50         node.left = buildTree (data , index);
51         node.right = buildTree (data , index);
52         return node;
53     }
54     
55     public int getValue(String data ,int index) {
56         int sign = data.charAt(index) == '-' ? -1 : 1;
57         int sum = data.charAt(index) == '-' ? 0 : data.charAt(index) - '0';
58         index++;
59         while(data.charAt(index) != ',') {
60             sum = sum * 10 + data.charAt(index) - '0';
61             index++;
62         }
63         return sum * sign;
64      }
65 }

3ms

 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 "";
16         }
17         
18         StringBuilder sb = new StringBuilder();
19         serialize(root, sb);
20         
21         return sb.toString();
22     }
23     
24     public void serialize(TreeNode node, StringBuilder sb) {
25         sb.append(node.val);
26         sb.append(",");
27         
28         if (node.left != null) {
29             serialize(node.left, sb);
30         }
31         else {
32             sb.append("/");
33         }
34         
35         if (node.right != null) {
36             serialize(node.right, sb);
37         }
38         else {
39             sb.append("/");
40         }
41     }
42     
43     private char chs[];
44     private int start;
45 
46     // Decodes your encoded data to tree.
47     public TreeNode deserialize(String data) {        
48         chs = data.toCharArray();
49         start = 0;
50         
51         return deserialize();
52     }
53     
54     private TreeNode deserialize() {
55         TreeNode root = null;
56         StringBuilder sb = new StringBuilder();
57         int i;
58         
59         for (i = start; i < chs.length; i++) {
60             if (chs[i] == ',') {
61                 break;
62             }
63             
64             if (chs[i] == '/') {
65                 break;
66             }
67             
68             sb.append(chs[i]);
69         }
70         
71         start = i + 1;
72         
73         if (sb.length() == 0) {
74             return root;
75         }
76         
77         root = new TreeNode(Integer.valueOf(sb.toString()));
78         root.left = deserialize();
79         root.right = deserialize();
80         
81         return root;
82     }
83 }
84 
85 // Your Codec object will be instantiated and called as such:
86 // Codec codec = new Codec();
87 // codec.deserialize(codec.serialize(root));

4ms

 1 public class Codec {
 2     public String serialize(TreeNode root) {
 3         StringBuilder builder = new StringBuilder();
 4         serialize(root, builder);
 5         return builder.toString();
 6     }
 7     
 8     private void serialize(TreeNode node, StringBuilder builder) {
 9         if (builder.length() > 0) builder.append(',');
10         if (node == null) {
11             builder.append('#');
12             return;
13         }
14         builder.append(node.val);
15         serialize(node.left, builder);
16         serialize(node.right, builder);
17     }
18     
19     public TreeNode deserialize(String data) {
20         return deserialize(data, new int[]{0});
21     }
22     
23     private TreeNode deserialize(String data, int[] i) {
24         int left = i[0], right = i[0];
25         while (right < data.length() && data.charAt(right) != ',') right++;
26         TreeNode node = right > left ? fromValue(data.substring(left, right)) : null;
27         i[0] = ++right;
28         if (node != null) {
29             node.left = deserialize(data, i);
30             node.right = deserialize(data, i);
31         }
32         return node;
33     }
34     
35     private TreeNode fromValue(String value) {
36         return "#".equals(value) ? null : new TreeNode(Integer.valueOf(value));
37     }
38 }

5ms

 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     int index = 0;
13     // Encodes a tree to a single string.
14     public String serialize(TreeNode root) {
15         StringBuilder sb = new StringBuilder();
16         serialize(root, sb);
17         System.out.println(sb);
18         return sb.toString();
19     }
20     public void serialize(TreeNode root,StringBuilder sb) {
21         if(root==null){
22             sb.append("#,");
23             return;
24         }
25         sb.append(root.val+",");
26         serialize(root.left,sb);
27         serialize(root.right,sb); 
28     }
29 
30     // Decodes your encoded data to tree.
31     public TreeNode deserialize(String data) {
32         index = 0;
33         return deserialize1(data);
34     }
35     
36     public TreeNode deserialize1(String data){
37         if(index>=data.length()) return null;
38         if(data.charAt(index)=='#'){
39             index+=2;
40             return null;
41         }
42         int cIndex = data.indexOf(',',index);
43         if(cIndex==-1)cIndex = data.length();
44         //System.out.printf("index %d cIndex %d \n",index,cIndex);
45         TreeNode node = new TreeNode(Integer.valueOf(data.substring(index,cIndex)));
46         index = cIndex+1;
47         node.left = deserialize1(data);
48         node.right = deserialize1(data);
49         return node;
50     }
51 }
52 
53 // Your Codec object will be instantiated and called as such:
54 // Codec codec = new Codec();
55 // codec.deserialize(codec.serialize(root));

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!