[英]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;
}
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). 您可能只想获得两个值中的最小值(告诉您到最近值的距离)。
Instead of 代替
dist =closeLeaf(n.getLeft()) + closeLeaf(n.getRight()); 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. 对于遇到的每个节点递增dist
,使用一个static / class成员变量,每次调用closeLeaf
函数时该变量都会递增。
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. 将递归限制为查找叶子,当找到一个叶子时, dist
的值将为您提供最接近叶子的高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.