-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path297.二叉树的序列化与反序列化.java
54 lines (48 loc) · 1.38 KB
/
297.二叉树的序列化与反序列化.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
* @lc app=leetcode.cn id=297 lang=java
*
* [297] 二叉树的序列化与反序列化
*/
// @lc code=start
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null)
return "#";
return root.val + "," + serialize(root.left) + "," + serialize(root.right);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] datas = data.split(",");
ArrayList<String> nodes = new ArrayList<String>(Arrays.asList(datas));
return deserialize(nodes);
}
private TreeNode deserialize(List<String> nodes) {
if (nodes.isEmpty())
return null;
String val = nodes.remove(0);
if (val.equals("#"))
return null;
TreeNode root = new TreeNode(Integer.parseInt(val));
root.left = deserialize(nodes);
root.right = deserialize(nodes);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));
// @lc code=end