Reputation: 137
Im having trouble with a method that finds the height of the closest leaf. What i have just counts all of the leafs. would i have to separate the recursive calls into two conditional statements to check each one independently? any help or suggestions would be appreciated
this is my method
//find the distance to the closest leaf
public int closeLeaf()
{
int distance;
return distance = closeLeaf(root);
}
private int closeLeaf(StringNode n)
{
int dist = 0;
if(n == null)
{
dist = 0;//empty tree
}
else if(n.getLeft()== null && n.getRight()== null)
{
dist++;
}
else
{
dist =closeLeaf(n.getLeft()) + closeLeaf(n.getRight());
}
return dist;
}
Upvotes: 1
Views: 1312
Reputation: 783
Instead of
dist =closeLeaf(n.getLeft()) + closeLeaf(n.getRight());
which increments dist
for every node encountered, use a static/class member variable that gets incremented each time the closeLeaf
function is called.
Limit the recursion to finding a leaf, and the value of dist
when you find one will give you the height of the closest leaf.
Upvotes: 1
Reputation: 54242
Please don't do this:
int distance;
return distance = closeLeaf(root);
Just:
return closeLeaf(root);
Here you're adding up the distance to each leaf:
dist = closeLeaf(n.getLeft()) + closeLeaf(n.getRight());
You probably just want to get the minimum of the two values (to tell you the distance to the closest one).
Upvotes: 3