简体   繁体   中英

java binary search tree find closest leaf

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;

}

Returning values

Please don't do this:

int distance;
return distance = closeLeaf(root);

Just:

return closeLeaf(root);

On to the real question

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).

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM