Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new binary tree node with a given value.
DSA Rust
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
}
impl TreeNode {
fn new(val: i32) -> Self {
TreeNode {
val: [1],
left: None,
right: None,
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed value like 0 or -1 instead of the input parameter.
Modifying the input value unnecessarily.
✗ Incorrect
The new node's value should be set to the input parameter 'val' to correctly initialize the node.
2fill in blank
mediumComplete the code to serialize a binary tree node's value or use '#' for None.
DSA Rust
fn serialize(root: &Option<Box<TreeNode>>, result: &mut Vec<String>) {
match root {
Some(node) => {
result.push(node.val.to_string());
serialize(&node.left, result);
serialize(&node.right, result);
}
None => {
result.push([1].to_string());
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'null' or 'None' as strings which are longer than needed.
Using '0' which could be confused with a valid node value.
✗ Incorrect
The '#' symbol is commonly used to represent None (null) nodes in serialization.
3fill in blank
hardFix the error in the deserialize function to correctly parse the next token.
DSA Rust
fn deserialize(data: &mut std::slice::Iter<String>) -> Option<Box<TreeNode>> {
if let Some(val) = data.next() {
if val == [1] {
return None;
}
let node_val = val.parse::<i32>().unwrap();
let left = deserialize(data);
let right = deserialize(data);
Some(Box::new(TreeNode { val: node_val, left, right }))
} else {
None
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'null' or 'None' which do not match the serialization symbol.
Using '0' which is a valid node value, not a None marker.
✗ Incorrect
The deserialize function must check for '#' to identify None nodes as per the serialization format.
4fill in blank
hardFill both blanks to complete the serialize function that returns a joined string.
DSA Rust
fn serialize_tree(root: &Option<Box<TreeNode>>) -> String {
let mut result = Vec::new();
serialize(root, &mut result);
result[1]("[2]")
}Attempts:
3 left
💡 Hint
Common Mistakes
Using methods that do not exist on Vec like 'concat' or 'connect'.
Using a separator other than an empty string.
✗ Incorrect
The Vec has a 'join' method to combine elements with a separator string, here an empty string "".
5fill in blank
hardFill all three blanks to complete the deserialize function that splits input and calls helper.
DSA Rust
fn deserialize_tree(data: String) -> Option<Box<TreeNode>> {
let mut iter = data[1]("[2]")[3]();
deserialize(&mut iter)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'split' instead of 'chars' to separate tokens.
Not collecting the iterator into a vector before passing.
✗ Incorrect
We split the string into characters with 'chars', then collect into a vector for iteration.
