Untitled
unknown
plain_text
a year ago
1.8 kB
17
Indexable
public class Codec {
// Serialize the tree to a string
public String serialize(TreeNode root) {
if (root == null) {
return "";
}
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node == null) {
sb.append("null,");
} else {
sb.append(node.val).append(",");
queue.add(node.left);
queue.add(node.right);
}
}
// Remove the trailing comma
sb.setLength(sb.length() - 1);
return sb.toString();
}
// Deserialize the string back to a tree
public TreeNode deserialize(String data) {
if (data == null || data.isEmpty()) {
return null;
}
String[] nodes = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < nodes.length) {
TreeNode current = queue.poll();
// Process the left child
if (!nodes[i].equals("null")) {
current.left = new TreeNode(Integer.parseInt(nodes[i]));
queue.add(current.left);
}
i++;
// Process the right child
if (i < nodes.length && !nodes[i].equals("null")) {
current.right = new TreeNode(Integer.parseInt(nodes[i]));
queue.add(current.right);
}
i++;
}
return root;
}
}Editor is loading...
Leave a Comment