Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Getting the height of a binary tree

843785Nov 5 2008 — edited Nov 6 2008
So I am trying to create a method in my binary tree class that returns and integer that represents the height of the tree.
I tried to do this recursively and it seems the numbers are close to the actual ones, but never exact and I haven't really been able to find out where the problem lies. This is my code:
public int getHeight()
	{
		int height;
		height = getHeightRecur(root);
		return height;
	}
	public int getHeightRecur(BinTreeNode node)
	{ 
		int theight;
		if(node == null)
			theight = 0;
		else
			theight = 1 + getMax(getHeightRecur(node.leftN), getHeightRecur(node.rightN));
		return theight;
	}
	private int getMax(int x, int y)
	{
		int result = 0;
		if(x>y)
			result = x;
		if(y>x)
			result = y;
		return result;
	}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 4 2008
Added on Nov 5 2008
8 comments
110 views