Comp Sci How can I efficiently find the closest leaf in a Java Binary Search Tree?

  • Thread starter Thread starter apiwowar
  • Start date Start date
  • Tags Tags
    Java
Click For Summary
The discussion focuses on finding the closest leaf in a Java Binary Search Tree, with the user struggling to implement a method that accurately determines the height of the closest leaf. The current approach counts all leaves instead of identifying the closest one, prompting a suggestion to use separate conditional statements for recursive calls. A breadth-first search is recommended as an alternative method, allowing for a top-down approach to detect leaves efficiently. The user seeks further assistance in refining their code to achieve the desired functionality. The conversation highlights the need for a more targeted recursive strategy or a breadth-first search to improve the leaf detection process.
apiwowar
Messages
94
Reaction score
0
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

Code:
//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;

}
 
Physics news on Phys.org
A breadth first search would hit the nodes top down. You could check if its a leaf as you go top down. Stop it once detected. Never coded a breadth first to help much further than that.
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 18 ·
Replies
18
Views
2K