Minimum Absolute Difference in BST
Description
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:1
3 / 2Output: 1
Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note:
- There are at least two nodes in this BST.
- This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const getMinimumDifference = (root) => {
let min = Infinity
let previous = null
const aux = (node) => {
if (!node) {
return
}
if (node.left) {
aux(node.left)
}
const possibleMin = Math.abs(node.val - previous)
if ((previous !== null) && (possibleMin < min)) {
min = possibleMin
}
previous = node.val
if (node.right) {
aux(node.right)
}
}
aux(root)
return min
}