我需要遍历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
}
答案 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))
}