Complete the code to define a binary tree node struct with left and right children.
struct Node {
data: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Node {
fn new(data: i32) -> Self {
Node {
data,
left: [1],
right: None,
}
}
}The left child is initially empty, so we use None to indicate no child.
Complete the code to check if a node is a leaf (no children).
fn is_leaf(node: &Option<Box<Node>>) -> bool {
if let Some(n) = node {
n.left.is_none() && n.right.[1]()
} else {
false
}
}To check if the right child is empty, use is_none().
Fix the error in the function that prints the left boundary excluding leaves.
fn print_left_boundary(node: &Option<Box<Node>>) {
if let Some(n) = node {
if !is_leaf(node) {
print!("{} ", n.data);
if n.left.is_some() {
print_left_boundary(&n.[1]);
} else {
print_left_boundary(&n.right);
}
}
}
}To continue down the left boundary, recurse on n.left.
Fill both blanks to collect leaf nodes in left-to-right order.
fn print_leaves(node: &Option<Box<Node>>) {
if let Some(n) = node {
print_leaves(&n.[1]);
if is_leaf(node) {
print!("{} ", n.data);
}
print_leaves(&n.[2]);
}
}To print leaves left to right, recurse left child first, then right child.
Fill all three blanks to print the boundary traversal of the binary tree.
fn print_boundary(root: &Option<Box<Node>>) {
if root.is_none() {
return;
}
let r = root.as_ref().unwrap();
print!("{} ", r.data); // root
print_left_boundary(&r.[1]);
print_leaves(&r.[2]);
print_leaves(&r.[3]);
print_right_boundary(&r.right);
}Start left boundary from left child, leaves from left and right children respectively.
