Complete the code to return the height of a binary tree.
function height(root: TreeNode | null): number {
if (root === null) {
return [1];
}
return 1 + Math.max(height(root.left), height(root.right));
}The height of an empty tree is 0, so we return 0 when the node is null.
Complete the code to calculate the height by comparing left and right subtree heights.
return 1 + Math.[1](height(root.left), height(root.right));
The height of a binary tree is 1 plus the maximum height of its left and right subtrees.
Fix the error in the base case to correctly handle empty nodes.
if (root [1] null) { return 0; }
Use strict equality (===) to check if root is exactly null for type safety.
Fill both blanks to complete the recursive height calculation.
const leftHeight = height(root.[1]); const rightHeight = height(root.[2]); return 1 + Math.max(leftHeight, rightHeight);
We calculate height of left and right subtrees by accessing root.left and root.right.
Fill all three blanks to create a function that returns the height of a binary tree.
function height([1]: TreeNode | null): number { if ([2] === null) { return [3]; } return 1 + Math.max(height([2].left), height([2].right)); }
The function parameter is named 'root'. We check if 'root' is null and return 0 if yes.