Java Reference
In-Depth Information
private int countLevels(IntTreeNode root) {
...
}
You can again use the definition that a tree is either empty or a root node with left
and right subtrees. If it is empty, then it has no levels at all (0 levels):
private int countLevels(IntTreeNode root) {
if (root == null) {
return 0;
} else {
...
}
}
If the tree is not empty, then it is a root node with left and right subtrees. In this
case, the data stored in the tree don't matter. We are asking a question about the
structure of the tree. To solve this problem, you should think about what a recursive
call on the subtrees would return. It would tell you the number of levels in the left
subtree and the number of levels in the right subtree. Those answers might match
(they might have the same number of levels), but often you'll find that one subtree
has more levels than the other. In that case, what matters more is the subtree that has
more levels, because that determines the number of levels in the overall tree. Here's a
first attempt at writing the method:
private int countLevels(IntTreeNode root) {
if (root == null) {
return 0;
} else {
return Math.max(countLevels(root.left), countLevels(root.right));
}
}
Let's think about a specific case. Consider the following tree:
8
7
4
2
9
Search WWH ::




Custom Search