首页 > 解决方案 > 在 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));

    }

标签: javaalgorithmdata-structures

解决方案


推荐阅读