Complete the code to define the TreeNode struct with optional left and right children.
struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
};
impl TreeNode {
fn new(val: i32) -> Self {
TreeNode {
val,
left: [1],
right: None,
}
}
}Some with a new node instead of None.Option.The left child is initially empty, so we use None to indicate no child.
Complete the code to check if the current node is None in the LCA function.
fn lowest_common_ancestor(root: &Option<Box<TreeNode>>, p: i32, q: i32) -> Option<i32> {
if [1] {
return None;
}
// rest of the code
}is_some() which checks for presence, not absence.== None which is less idiomatic in Rust.We check if the root is None using is_none() to stop recursion.
Fix the error in the recursive call to lowest_common_ancestor for the left subtree.
let left = lowest_common_ancestor(&[1].left, p, q);unwrap() directly on root which is an Option reference.root without dereferencing.We use as_ref() to get a reference to the boxed node, then unwrap() to access the inner TreeNode.
Fill both blanks to correctly compare the current node's value with p and q.
let val = [1].val; if val == [2] || val == q { return Some(val); }
root.unwrap() directly without as_ref().p and q in comparisons.We get the current node's value by unwrapping the reference, then compare it with p and q.
Fill all three blanks to return the correct lowest common ancestor based on left and right recursive results.
if left.is_some() && right.is_some() { return Some([1]); } if left.is_some() { return [2]; } return [3];
root instead of val when both sides are Some.right when left is Some and right is None.If both left and right are found, current node is LCA (val). Otherwise, return whichever side is Some.
