在BST中查找比给定值更高的值

时间:2017-06-04 16:24:03

标签: java recursion data-structures binary-tree binary-search-tree

我试图在二元搜索树中找到比给定值更高的值,仅仅是为了好玩和过度学习。到目前为止,我已经用它的逻辑在纸上绘制了一个强大的功能。但是,当我运行它时,它并没有给出预期的结果。例如,30, 25, 98, 23, 28, 97, 99, 29包含在BST中。我试图获得的值高于28 5,但输出为2。方法中的问题在哪里?我遍历树中的所有节点,是否有更有效的解决方案?

public int findMax(Node<E> localRoot, E target) {
        if (localRoot == null) return 0;

        int cmpResult = target.compareTo(localRoot.data);
        int valL = findMax(localRoot.left, target) + cmpResult < 0 ? 1 : 0;
        int valR = findMax(localRoot.right, target) + cmpResult < 0 ? 1 : 0;
        return valL + valR;
}

1 个答案:

答案 0 :(得分:1)

最后,由于这个逻辑,第一个函数调用总是最多返回1 + 1:

int valL = findMax(localRoot.left, target) + cmpResult < 0 ? 1 : 0;
int valR = findMax(localRoot.right, target) + cmpResult < 0 ? 1 : 0;

由于操作顺序,它调用了多少级别并不重要。 valL和valR将始终为0或1,因为它正在测试(findMax(localRoot.right,target)+ cmpResult)是否为&lt; 0,十分配值为0或1.使用括号尝试,以便添加findMax的结果。像这样:

int valL = findMax(localRoot.left, target) + (cmpResult < 0 ? 1 : 0);
int valR = findMax(localRoot.right, target) + (cmpResult < 0 ? 1 : 0);

- 编辑 -

好的,我意识到我错过了另一个重要问题:您将本地比较结果添加到每个节点的左右计算中。这将导致值太高!您需要保持本地节点比较独立于左右节点比较。试试这个:

int cmpResult = target.compareTo(localRoot.data);
int localNodeVal = cmpResult < 0 ? 1 : 0; // This is the value for the current node by itself.
int valL = findMax(localRoot.left, target);
int valR = findMax(localRoot.right, target);
// Add the local node result with the evaluation of the left and right side.
return localNodeVal + valL + valR;
相关问题