Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print the root node's value first in preorder traversal.
DSA Rust
fn preorder(node: &Option<Box<TreeNode>>) {
if let Some(ref n) = *node {
println!("{}", [1]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Trying to print 'node.val' which is an Option and does not have 'val' directly.
Printing left or right child instead of the root node's value.
✗ Incorrect
In preorder traversal, we first visit the root node's value. Here, 'n' is the current node, so we print 'n.val'.
2fill in blank
mediumComplete the code to recursively traverse the left subtree in preorder.
DSA Rust
fn preorder(node: &Option<Box<TreeNode>>) {
if let Some(ref n) = *node {
println!("{}", n.val);
preorder(&[1]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node.left' which is an Option reference, but 'node' is already an Option.
Calling preorder on the right child instead of the left.
✗ Incorrect
After visiting the root, preorder traversal visits the left subtree. The left child is 'n.left'.
3fill in blank
hardFix the error in the code to correctly traverse the right subtree after the left subtree in preorder.
DSA Rust
fn preorder(node: &Option<Box<TreeNode>>) {
if let Some(ref n) = *node {
println!("{}", n.val);
preorder(&n.left);
preorder(&[1]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node.right' which is an Option reference, but 'node' is already an Option.
Repeating 'n.left' instead of using 'n.right'.
✗ Incorrect
After traversing the left subtree, preorder traversal visits the right subtree. The right child is 'n.right'.
4fill in blank
hardFill both blanks to complete the preorder traversal function that prints root, then left, then right.
DSA Rust
fn preorder(node: &Option<Box<TreeNode>>) {
if let Some(ref n) = *node {
println!("{}", [1]);
preorder(&[2]);
preorder(&n.right);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node.val' or 'node.left' which are not directly accessible.
Swapping left and right subtree calls.
✗ Incorrect
We print the root value 'n.val', then recursively traverse the left subtree 'n.left', and finally the right subtree.
5fill in blank
hardFill all three blanks to complete the preorder traversal that prints root, then left, then right subtree recursively.
DSA Rust
fn preorder(node: &Option<Box<TreeNode>>) {
if let Some(ref n) = *node {
println!("{}", [1]);
preorder(&[2]);
preorder(&[3]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node.val' instead of 'n.val'.
Mixing up left and right subtree references.
✗ Incorrect
Preorder traversal visits root 'n.val', then left subtree 'n.left', then right subtree 'n.right'.
