Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new tree node with a value.
DSA Rust
struct TreeNode {
value: i32,
children: Vec<Box<TreeNode>>,
}
impl TreeNode {
fn new(val: i32) -> Box<Self> {
Box::new(TreeNode {
value: [1],
children: Vec::new(),
})
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the field name 'value' instead of the parameter 'val'.
Trying to assign 'children' here.
✗ Incorrect
The constructor takes val as input and assigns it to the value field.
2fill in blank
mediumComplete the code to add a child node to a tree node.
DSA Rust
impl TreeNode {
fn add_child(&mut self, child: Box<TreeNode>) {
self.children.[1](child);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using extend() which expects an iterator.
Using insert() without an index.
✗ Incorrect
Vec uses push() to add a single element at the end.
3fill in blank
hardFix the error in the code to check if a tree node has children.
DSA Rust
impl TreeNode {
fn has_children(&self) -> bool {
self.children.[1]() > 0
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using length() which is not a Vec method.
Using size() or count() which do not exist for Vec.
✗ Incorrect
Vec in Rust uses len() to get the number of elements.
4fill in blank
hardFill both blanks to create a tree node and add a child.
DSA Rust
let mut root = TreeNode::[1](10); root.children.[2](TreeNode::new(20));
Attempts:
3 left
💡 Hint
Common Mistakes
Using insert() without index.
Using extend() to add a single child.
✗ Incorrect
Use new() to create a node and push() to add a child.
5fill in blank
hardFill all three blanks to create a tree, add children, and check if root has children.
DSA Rust
let mut root = TreeNode::[1](5); root.children.[2](TreeNode::new(15)); let has_kids = root.children.[3]() > 0;
Attempts:
3 left
💡 Hint
Common Mistakes
Using insert() without index.
Using size() or length() instead of len().
✗ Incorrect
Create with new(), add child with push(), check length with len().
