-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodec.java
More file actions
85 lines (69 loc) · 2.03 KB
/
Codec.java
File metadata and controls
85 lines (69 loc) · 2.03 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* @lc app=leetcode id=297 lang=java
*
* [297] Serialize and Deserialize Binary Tree
*/
// @lc code=start
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.tree.TreeNode;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null)
return "null";
StringBuilder sb = new StringBuilder();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode curr = q.poll();
if (curr == null) {
sb.append("null,");
continue;
}
sb.append(curr.val).append(",");
q.add(curr.left);
q.add(curr.right);
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.equals("null"))
return null;
String[] arr = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(arr[0]));
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int i = 1;
// KEY Take away need to get more familar with leetcode TreeNode
while (!q.isEmpty() && i < arr.length) {
TreeNode curr = q.poll();
if (!arr[i].equals("null")) {
curr.left = new TreeNode(Integer.parseInt(arr[i]));
q.add(curr.left);
}
i++;
if (i < arr.length && !arr[i].equals("null")) {
curr.right = new TreeNode(Integer.parseInt(arr[i]));
q.add(curr.right);
}
i++;
}
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