530. Minimum Absolute Difference in BST

Posted on Jan 22, 2025

Solution

Implementation

class Solution {
    fun getMinimumDifference(root: TreeNode?): Int {
        var result = Int.MAX_VALUE
        var lastValue: Int? = null

        fun traverse(node: TreeNode?) {
            if (node == null) return

            traverse(node.left)
            if (lastValue != null)
                result = min(result, node.`val` - lastValue!!)
            lastValue = node.`val`
            traverse(node.right)
        }

        traverse(root)

        return result
    }
}