【发布时间】:2020-05-09 02:19:37
【问题描述】:
我正在尝试解决这个问题。我没有得到预期的输出
给定一个具有根节点的二叉搜索树 (BST),返回树中任意两个不同节点的值之间的最小差值。
例子:
输入:
root = [4,2,6,1,3,null,null]
输出:
1
说明:
注意 root 是 TreeNode 对象,而不是数组。
给定的树[4,2,6,1,3,null,null]如下图表示:
4
/ \
2 6
/ \
1 3
虽然这棵树的最小差值为 1,但它发生在节点 1 和节点 2 之间,也发生在节点 3 和节点 2 之间。
我试过这样
var minDiffInBST = function (root) {
let min = Number.MAX_VALUE
const getMin = (node) => {
if (node.left && node.right) {
console.log('both')
return Math.min(node.val - node.left.val, node.right.val - node.val)
} else if (node.right) {
console.log('right')
return node.right.val - node.val
} else if (node.left) {
console.log('left')
return node.val - node.left.val
} else {
return Number.MAX_VALUE
}
}
const preOrder = (root) => {
if (!root) {
return 0;
}
let x = getMin(root)
if (x < min)
min = x
preOrder(root.left)
preOrder(root.right)
}
preOrder(root)
return min
};
console.log(minDiffInBST({
"val": 90,
"left": {
"val": 69,
"left": {"val": 49, "left": null, "right": {"val": 52, "left": null, "right": null}},
"right": {"val": 89, "left": null, "right": null}
},
"right": null
}
))
得到输出3
预期输出 1
我的问题来自这里 https://leetcode.com/problems/minimum-distance-between-bst-nodes/
【问题讨论】:
标签: javascript binary-search-tree