有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在BST中查找最接近值的问题

我正在尝试编写一个函数,该函数接受BST和目标整数值,并返回与BST中包含的目标值最接近的值

然而,我的代码得到的是0,而不是10,这是本例的答案

有人能解释我的错误的基本概念吗

    public static int findClosestValueInBst(BST tree, int target) {
        int globalDiff = Integer.MAX_VALUE;
        int answer = 0;
        subFunction(tree, target, globalDiff, answer);
        return answer;
    }

private static void subFunction (BST tree, int target, int globalDiff, int answer) {
        if (tree == null) {
            return;
        }
        int localDiff = Math.abs(target - tree.value);
        if (localDiff < globalDiff) {
            globalDiff = localDiff;
            answer = tree.value;
        }
        subFunction(tree.left, target, globalDiff, answer);
        subFunction(tree.right, target, globalDiff, answer);
        return;
    }

    public static class BST {
        public int value;
        public BST left;
        public BST right;

        public BST(int value) {
            this.value = value;
        }
    }

    public static void main (String[] args) {
        BST first = new BST(1);
        BST second = new BST(2);
        BST third = new BST(10);
        BST fourth = new BST(5);
        BST fifth = new BST(4);

        first.left = second;
        first.right = third;
        second.left = fourth;
        second.right = fifth;

        System.out.println(findClosestValueInBst(first, 11));

    }

共 (0) 个答案