balanced() binary tree
I need to write a method that determines whether a binary tree is balanced. So first I'm going to have to determine the height of each side of the tree. But I'm having trouble understanding how I am going to count the max length of a subtree, without counting all the nodes in the subtree. This question is very difficult to ask for me, so 开发者_如何学编程you guys can understand.
// primary method
public int Height()
{
int h = height( root );
}
// recursive method
private int height( Node x )
{
if( x == null ) return 0;
count++;
height( x.left );
height( x.right );
return count;
}
Here is my code for calculating the max height of the tree. But i dont know how to determine just the left or right sides' height, and this method seems to count the amount of nodes in the tree itself.
This method will not even compile, because of the return;
statement - you need to return an int.
So, if(x == null)
, what should you return? What is the height of an empty tree?
Once you have that figured out, imagine your root has only a left-subtree (root.right == null
), and you know the height of the left-subtree. What should the height of the overall tree be?
What if it has only a right subtree?
Now, what if it has both?
Note that you don't need a global counting variable for any of this.
The height is 1 + max(left.height(), right.height()).
You should return a value instead of setting a variable (count, in your case), otherwise you'll go mad.
The height of a node is one more than the height of its tallest sub-node (hint: use Math.max
).
Adding to the hints I'll also point out that you really want to use recursion.
精彩评论