Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start serialization by calling the helper function on the root node.
DSA Java
public String serialize(TreeNode root) {
return [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling toString() on root does not serialize the tree.
Calling serialize on root.left misses the whole tree.
✗ Incorrect
We need to call the helper method serializeHelper with the root node to start serialization.
2fill in blank
mediumComplete the code to handle the base case in serialization when the node is null.
DSA Java
private String serializeHelper(TreeNode node) {
if (node == null) {
return [1];
}
// rest of code omitted
}Attempts:
3 left
💡 Hint
Common Mistakes
Using "null" or empty string can cause confusion during deserialization.
✗ Incorrect
We use "#" to represent null nodes in serialization.
3fill in blank
hardFix the error in deserialization by correctly parsing the next token from the queue.
DSA Java
private TreeNode deserializeHelper(Queue<String> nodes) {
String val = [1];
if (val.equals("#")) return null;
TreeNode node = new TreeNode(Integer.parseInt(val));
node.left = deserializeHelper(nodes);
node.right = deserializeHelper(nodes);
return node;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() causes infinite loop because the token is never removed.
Using element() throws exception if queue is empty.
✗ Incorrect
poll() removes and returns the head of the queue, which is needed to move forward in deserialization.
4fill in blank
hardFill both blanks to split the serialized string into tokens and create a queue for deserialization.
DSA Java
public TreeNode deserialize(String data) {
String[] nodes = data.[1](" ");
Queue<String> queue = new LinkedList<>();
queue.[2](Arrays.asList(nodes));
return deserializeHelper(queue);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using join instead of split causes errors.
Using offer adds one element, not a collection.
✗ Incorrect
We split the string by spaces and add all tokens to the queue for deserialization.
5fill in blank
hardFill all three blanks to complete the serializeHelper method that serializes the tree in preorder.
DSA Java
private String serializeHelper(TreeNode node) {
if (node == null) {
return "#";
}
return node.val + [1] + serializeHelper(node.left) + [2] + serializeHelper(node.right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using commas or semicolons can complicate splitting if not handled properly.
✗ Incorrect
We use spaces to separate node values in the serialized string for easy splitting during deserialization.
