Given a simple binary tree, what will be the printed levels of each node?
struct Node {
value: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
fn print_levels(node: &Option<Box<Node>>, level: usize) {
if let Some(n) = node {
println!("{}: Level {}", n.value, level);
print_levels(&n.left, level + 1);
print_levels(&n.right, level + 1);
}
}
fn main() {
let tree = Some(Box::new(Node {
value: 1,
left: Some(Box::new(Node {
value: 2,
left: None,
right: None,
})),
right: Some(Box::new(Node {
value: 3,
left: None,
right: None,
})),
}));
print_levels(&tree, 0);
}Remember, root node starts at level 0, children increase level by 1.
The root node (value 1) is at level 0. Its children (2 and 3) are at level 1.
In tree terminology, what is the height of a leaf node?
Height is the number of edges on the longest path from the node down to a leaf.
A leaf node has no children, so its height is 0.
Consider this Rust code that tries to print the depth of each node but prints wrong values. Identify the bug.
struct Node {
value: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
fn print_depth(node: &Option<Box<Node>>, depth: usize) {
if let Some(n) = node {
println!("{}: Depth {}", n.value, depth);
print_depth(&n.left, depth);
print_depth(&n.right, depth);
}
}
fn main() {
let tree = Some(Box::new(Node {
value: 10,
left: Some(Box::new(Node {
value: 20,
left: None,
right: None,
})),
right: Some(Box::new(Node {
value: 30,
left: None,
right: None,
})),
}));
print_depth(&tree, 0);
}Check how the depth parameter changes in recursive calls.
The depth parameter must increase by 1 when moving to child nodes to reflect correct depth.
What is the output of this Rust function that calculates the height of a binary tree?
struct Node {
value: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
fn height(node: &Option<Box<Node>>) -> usize {
match node {
None => 0,
Some(n) => {
let left_height = height(&n.left);
let right_height = height(&n.right);
1 + std::cmp::max(left_height, right_height)
}
}
}
fn main() {
let tree = Some(Box::new(Node {
value: 5,
left: Some(Box::new(Node {
value: 3,
left: None,
right: None,
})),
right: Some(Box::new(Node {
value: 8,
left: Some(Box::new(Node {
value: 7,
left: None,
right: None,
})),
right: None,
})),
}));
println!("Height: {}", height(&tree));
}Height counts nodes on the longest path from root to leaf.
The longest path is 5 -> 8 -> 7, which has 3 nodes, so height is 3.
In tree terminology, what is the level of the root node?
Level counts edges from the root to the node.
The root node is at level 0 because it has no parent.
