在JavaScript中进行递归二分搜索树遍历时返回一个值

时间:2020-07-14 01:50:05

标签: javascript binary-search-tree

sample BST structure

我需要遍历BST并返回最接近提供的目标整数值的节点值。

遍历可以如下进行:

function traverse(node, target, closestValue) {
    console.log(node.value);
    let potentialClosestValue = Math.abs(node.value - target)
    if (potentialClosestValue < closestValue) { closestValue = potentialClosestValue; }
    
    if (node.left) {
        traverse(node.left, target, closestValue)
    }
    if (node.right) {
        traverse(node.right, target, closestValue)
    }
}

function findClosestValueInBst(tree, target) {
    traverse(tree, target, Infinity)
}

我怎么知道整个树遍历已经完成?我可以在遍历函数的范围之外创建一个变量并将其返回,但是我可以以某种方式从递归函数中返回它吗?例如:

function findClosestValueInBst(tree, target, output) {
    return traverse(tree, target, Infinity, 0) // returns 13
}

1 个答案:

答案 0 :(得分:1)

function traverse(node, target, closestValue) {
    console.log(node.value);
    let potentialClosestValue = Math.abs(node.value - target)
    if (potentialClosestValue < Math.abs(closestValue - target)) { closestValue = node.value; }
    
    if (node.right) {
        let res = traverse(node.right, target, closestValue)
        if (Math.abs(res-target) < Math.abs(closestValue - target) closestValue = res
    }
    if (node.left) {
        let res = traverse(node.left, target, closestValue)
        if (Math.abs(res-target) < Math.abs(closestValue - target) closestValue = res 
    }
    return closestValue
}

function findClosestValueInBst(tree, target) {
    console.log(traverse(tree, target, Infinity))
}