Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to visit the left child first in inorder traversal.
DSA Rust
fn inorder(node: &Option<Box<TreeNode>>) {
if let Some(n) = node {
inorder(&n.[1]);
print!("{} ", n.val);
inorder(&n.right);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'right' instead of 'left' causes wrong traversal order.
Trying to access 'val' as a child causes errors.
✗ Incorrect
In inorder traversal, we first visit the left child, so we call inorder(&n.left).
2fill in blank
mediumComplete the code to print the current node's value in inorder traversal.
DSA Rust
fn inorder(node: &Option<Box<TreeNode>>) {
if let Some(n) = node {
inorder(&n.left);
print!("{} ", n.[1]);
inorder(&n.right);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Printing left or right instead of val causes wrong output.
Printing parent causes compilation error.
✗ Incorrect
We print the current node's value using n.val in inorder traversal after visiting left child.
3fill in blank
hardFix the error in the recursive call to visit the right child in inorder traversal.
DSA Rust
fn inorder(node: &Option<Box<TreeNode>>) {
if let Some(n) = node {
inorder(&n.left);
print!("{} ", n.val);
inorder(&n.[1]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'left' again causes infinite recursion.
Using 'val' or 'parent' causes errors.
✗ Incorrect
To complete inorder traversal, we must visit the right child using inorder(&n.right).
4fill in blank
hardFill both blanks to create a recursive inorder traversal that returns a vector of values.
DSA Rust
fn inorder_collect(node: &Option<Box<TreeNode>>, vals: &mut Vec<i32>) {
if let Some(n) = node {
inorder_collect(&n.[1], vals);
vals.push(n.[2]);
inorder_collect(&n.right, vals);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping left and right causes wrong order.
Using 'right' or 'parent' in blanks causes errors.
✗ Incorrect
We recursively visit left child (n.left) and push the current node's value (n.val) to the vector.
5fill in blank
hardFill all three blanks to create a function that returns a vector of inorder traversal values using map and flatten.
DSA Rust
fn inorder_values(node: &Option<Box<TreeNode>>) -> Vec<i32> {
node.as_ref().map(|n| {
let mut left_vals = inorder_values(&n.[1]);
left_vals.push(n.[2]);
left_vals.extend(inorder_values(&n.[3]));
left_vals
}).unwrap_or_else(Vec::new)
}Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up left and right causes wrong order.
Using 'parent' causes compilation errors.
✗ Incorrect
We collect values from left child (n.left), then current node's value (n.val), then right child (n.right).
