Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create the root node of a binary tree.
DSA Rust
let root = TreeNode::new([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Using None or negative values for the root node.
Using zero which might be valid but here 1 is preferred.
✗ Incorrect
The root node usually starts with a value, here 1 is used as the root value.
2fill in blank
mediumComplete the code to check if a node is a leaf (no children).
DSA Rust
fn is_leaf(node: &TreeNode) -> bool {
node.left.is_none() && node.[1].is_none()
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking parent or root instead of right child.
Using 'child' which is not a field.
✗ Incorrect
A leaf node has no left or right children, so we check if right is None.
3fill in blank
hardFix the error in the function to calculate the height of a tree node.
DSA Rust
fn height(node: Option<&TreeNode>) -> i32 {
if node.is_none() {
return 0;
}
let node = node.unwrap();
1 + std::cmp::max(height(node.left.as_ref()), [1])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using parent instead of right child.
Recursing on the same left child twice.
✗ Incorrect
Height is the max height between left and right children plus one.
4fill in blank
hardFill both blanks to calculate the depth of a node given its parent depth.
DSA Rust
fn depth(node: &TreeNode, parent_depth: i32) -> i32 {
if node.is_root() {
return 0;
}
[2] parent_depth [1] 1
}Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting instead of adding.
Not returning the depth value.
✗ Incorrect
Depth increases by 1 from parent, then return the new depth.
5fill in blank
hardFill all three blanks to create a function that returns the level of a node in the tree.
DSA Rust
fn level(node: &TreeNode) -> i32 {
if node.is_root() {
return [1];
}
let parent_level = level(node.[2].as_ref().unwrap());
parent_level [3] 1
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 for root level instead of 1.
Accessing left or right child instead of parent.
Subtracting instead of adding one.
✗ Incorrect
Root level is 1, level is parent's level plus one, and parent is accessed via 'parent'.
