so I need to find the max height of a binary tree but for some reason the result of the code provided below is off by 1. For example if the max height is 3 the following code will give me 2. if the max height is 4 the result will be 3. I am not sure why? the root is not considered for the calculations of the max height therefore i set leftCounter and rightCounter to be 0. any ideas?
public int getMaxHeight(BST.TreeNode<E> n) {
if(n == null) {
return 0;
}
int leftCounter = 0;
int rightCounter = 0;
if(n.left != null) {
leftCounter = getMaxHeight(n.left) +1 ;
}
if(n.right != null) {
rightCounter = getMaxHeight(n.right) +1 ;
}
if(leftCounter > rightCounter) {
return leftCounter;
}
else
return rightCounter;
}
the max height of this binary tree should be 3 : because of the elements 5,9,11. the root is not counted for the max height.
15
_____|____
10 21
___|___ __|__
9 14 16 24
|__
25
Your code actually returns the correct value; it's just that you misunderstand what the height of a tree means. The height is the number of edges on the longest path from root to leaf, not the number of nodes on the path. So the following tree
3
_____|____
4 5
___|___ __|__
6 7 8 9
has a height of 2, not 3. What you are looking for is the number of levels in the tree, not the height.
public int getNumberOfLevels(BST.TreeNode<E> n) {
if(n == null) return 0;
int left = getNumberOfLevels(n.left);
int right = getNumberOfLevels(n.right);
return 1 + Math.max(left, right);
}
you can initialize leftCounter, and RightCounter by 1. Reason being if(n==null) -> false
which means height is atleast 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.