Complete the code to return 0 when the tree node is empty.
fn height(node: &Option<Box<TreeNode>>) -> i32 {
if node.is_none() {
return [1];
}
1
}When the node is empty (None), the height is 0 because there are no nodes.
Complete the code to get the left child of the current node.
fn height(node: &Option<Box<TreeNode>>) -> i32 {
if node.is_none() {
return 0;
}
let left_height = height(&node.as_ref().unwrap().[1]);
1
}To get the left child of the current node, use left field.
Fix the error in the code to compute the maximum height between left and right subtrees.
fn height(node: &Option<Box<TreeNode>>) -> i32 {
if node.is_none() {
return 0;
}
let left_height = height(&node.as_ref().unwrap().left);
let right_height = height(&node.as_ref().unwrap().right);
1 + [1](left_height, right_height)
}We take the maximum of left and right subtree heights to find the height of the tree.
Fill both blanks to complete the recursive height function correctly.
fn height(node: &Option<Box<TreeNode>>) -> i32 {
if node.is_none() {
return [1];
}
let left_height = height(&node.as_ref().unwrap().[2]);
let right_height = height(&node.as_ref().unwrap().right);
1 + std::cmp::max(left_height, right_height)
}Return 0 for empty node and access left child with left.
Fill all three blanks to complete the height function with variable names and return statement.
fn height([1]: &Option<Box<TreeNode>>) -> i32 { if [2].is_none() { return 0; } let left_height = height(&[3].as_ref().unwrap().left); let right_height = height(&[3].as_ref().unwrap().right); 1 + std::cmp::max(left_height, right_height) }
The parameter and variable used is node consistently.
