JSFiddle - React, Tailwind, and code Playground
by Alex Myronov
JavaScript
/**
* @param {TreeNode} root
* @return {number}
*/
var minDiffInBST = function(root) {
if (!root) return 0
let min = Infinity
let prev = null
const minDiff = (root) => {
if (root.left) minDiff(root.left)
if (prev) {
min = Math.min(min, Math.abs(prev.val - root.val))
}
prev = root
if (root.right) minDiff(root.right)
return min
}
return minDiff(root)
};
function TreeNode(val) {
this.val = val
this.left = this.right = null
}
const t = new TreeNode(4)
t.left = new TreeNode(2)
t.left.left = new TreeNode(1)
t.left.right = new TreeNode(3)
t.right = new TreeNode(6)
console.log(minDiffInBST(t))