Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to call the postorder traversal function recursively on the left child.
DSA Rust
fn postorder(node: &Option<Box<TreeNode>>) {
if let Some(n) = node {
postorder(&n.[1]);
println!("{}", n.val);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling postorder on the right child first.
Trying to access a non-existent field like parent.
✗ Incorrect
In postorder traversal, we first visit the left child, so we call postorder on n.left.
2fill in blank
mediumComplete the code to call the postorder traversal function recursively on the right child.
DSA Rust
fn postorder(node: &Option<Box<TreeNode>>) {
if let Some(n) = node {
postorder(&n.left);
postorder(&n.[1]);
println!("{}", n.val);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling postorder on left child twice.
Using incorrect field names.
✗ Incorrect
After visiting the left child, postorder visits the right child, so call postorder on n.right.
3fill in blank
hardFix the error in printing the node value in postorder traversal.
DSA Rust
fn postorder(node: &Option<Box<TreeNode>>) {
if let Some(n) = node {
postorder(&n.left);
postorder(&n.right);
println!("[1]", n.val);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Printing n.val directly without a format string.
Using a string literal without {} placeholder.
✗ Incorrect
The println! macro needs a format string with {} to print the value of n.val.
4fill in blank
hardFill both blanks to create a postorder traversal that collects values into a vector.
DSA Rust
fn postorder_collect(node: &Option<Box<TreeNode>>, vals: &mut Vec<i32>) {
if let Some(n) = node {
postorder_collect(&n.[1], vals);
postorder_collect(&n.[2], vals);
vals.push(n.val);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping left and right children.
Using invalid field names.
✗ Incorrect
Postorder visits left child first, then right child, so blanks are filled with left and right respectively.
5fill in blank
hardFill all three blanks to create a postorder traversal that returns a vector of values.
DSA Rust
fn postorder_return(node: &Option<Box<TreeNode>>) -> Vec<i32> {
if let Some(n) = node {
let mut vals = postorder_return(&n.[1]);
vals.extend(postorder_return(&n.[2]));
vals.push(n.[3]);
vals
} else {
Vec::new()
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using root instead of val for node value.
Swapping left and right children.
✗ Incorrect
We collect values from left and right children, then push the current node's val.
