简体   繁体   中英

Returning a value at the end of a recursive binary search tree traversal in JavaScript

样本 BST 结构

I need to traverse a BST and return the node value that is closest to the supplied target integer value.

The traversal can be done as follows:

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

How do I know that the entire tree traversal has finished? I can create a variable out of scope of the traverse function and return that, but can I return it from the recursive function somehow? eg:

function findClosestValueInBst(tree, target, output) {
    return traverse(tree, target, Infinity, 0) // returns 13
}
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))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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