-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL297.java
More file actions
45 lines (43 loc) · 1.38 KB
/
L297.java
File metadata and controls
45 lines (43 loc) · 1.38 KB
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
public class L297 {
/**
* 297. Serialize and Deserialize Binary Tree https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
*
* @timeComplexity O(n)
* @spaceComplexity O(n)
*/
static class Codec {
int readIndex = 0;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuffer sb = new StringBuffer();
serialize(root, sb);
return sb.toString();
}
private void serialize(TreeNode root, StringBuffer sb) {
if (root == null) {
sb.append('#');
} else {
sb.append(root.val);
}
sb.append(' ');
if (root != null) {
serialize(root.left, sb);
serialize(root.right, sb);
}
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
return deserialize(data.split(" "));
}
private TreeNode deserialize(String[] input) {
if (input[readIndex].equals("#")) {
readIndex++;
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(input[readIndex++]));
root.left = deserialize(input);
root.right = deserialize(input);
return root;
}
}
}