Complete the code to return the height of the binary tree.
public int height(Node root) {
if (root == null) {
return [1];
}
return 1 + Math.max(height(root.left), height(root.right));
}The height of an empty tree is 0, so when the node is null, we return 0.
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 node 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]) { return 0; }
The base case checks if the node is null, not zero or false.
Fill both blanks to complete the recursive height calculation.
int leftHeight = height(root.[1]); int rightHeight = height(root.[2]);
We recursively find the height of the left and right children of the current node.
Fill all three blanks to complete the height method with base case and recursive step.
public int height(Node [1]) { if ([2] == null) { return [3]; } return 1 + Math.max(height([2].left), height([2].right)); }
The method takes a node parameter. The base case checks if the node is null and returns 0. Then it recursively calculates height.
