Question 6
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
public class Main {
static class Node {
int key;
Node left, right;
Node(int key) { this.key = key; }
}
static int height(Node n) {
if (n == null) return 0;
else if (n.left != null || n.right != null) return 1 + Math.max(height(n.left), height(n.right));
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
System.out.println(height(root));
}
}
- A Recursion is not allowed in static methods
- B A leaf (both children null) reaches the end of the method without a return; javac reports "missing return statement" – the else-if should simply be return 1 + … Correct
- C Math.max cannot take method calls
- D height must be declared before Node
Correct Answer: Option B
Every path through a non-void method must return a value; the compiler does not reason about which conditions are possible.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!