繁体   English   中英

返回二叉树范围内的节点数

[英]Returning the number of nodes within a range in a binary tree

我正在尝试编写一种方法,该方法返回二叉树中具有范围之间值的节点数。

如果请求的完整代码在这里:

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 都给他的孩子打电话的原因。 它会发生无限的时间。 您需要在 function 中将 child 作为 root 传递。 然后你可以数数。

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;
}

试试这个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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