返回二进制树中某个范围内的节点数



我正在尝试编写一个方法,该方法返回二进制树中值介于范围之间的节点数。

这里如果完整的代码要求:

public class StaffInfo {
final String name;
final int monthHired;
public StaffInfo(String name, int monthHired){
this.name = name;
this.monthHired = monthHired;
}

public class StaffTree implements Iterable<StaffInfo>{
public StaffNode root;
public StaffTree(StaffInfo c) {
this.root = new StaffInfo(c);
}
private StaffTree(StaffNode c) {
this.root = c;
}
class StaffNode {
StaffInfo data;
StaffNode senior;
StaffNode same;
StaffNode junior;
public StaffNode(StaffInfo data) {
this.data = data;
this.senior = null;
this.same = null;
this.junior = null;
}

以下是我遇到问题的方法的代码:

public int numInRange(int monthMin, int monthMax) {
int count = 0;
if (monthMin > monthMax) {
return 0;
}
if (root.data.monthHired >= monthMin && root.data.monthHired <= monthMax) {
count++;
}
if (root.senior != null) {
root.senior.numInRange(monthMin, monthMax);
}
if (root.same != null) {
root.same.numInRange(monthMin, monthMax);
}
if (root.junior != null) {
root.junior.numInRange(monthMin, monthMax);
}
return count;

我在模仿一个办公室,这样每个节点都可以有一个大四、大三或相同的孩子(由招聘日期决定(。monthMin和monthMax都是整数,表示自2015年1月以来的月份数。

当我运行上面的代码时,我会得到一个StackOverFlowError。

感谢您的帮助!

如果问题不清楚,请在评论中告诉我,我会立即编辑。

您使用root作为全局变量,这就是为什么每次root调用他的孩子。它将在无限的时间内发生。您需要在函数中将child作为根传递。那么你就可以数数了。

public int numInRange(Root root, int monthMin, int monthMax) {
int count = 0;
if (monthMin > monthMax) {
return 0;
}
if (root.data.monthHired >= monthMin && root.data.monthHired <= monthMax) {
count++;
}
if (root.senior != null) {
root.senior.numInRange(root.senior,monthMin, monthMax);
}
if (root.same != null) {
root.same.numInRange(root.same,monthMin, monthMax);
}
if (root.junior != null) {
root.junior.numInRange(root.junior,monthMin, monthMax);
}
return count;
}

试试这个。

相关内容

最新更新