Minimum Absolute Difference in BST

Easy#530in-order

You get the root of a binary search tree with at least two nodes. Return the smallest difference between the values of any two nodes. Our tree: 20 with children 9 and 31; 9 has children 4 and 15; 31 has only a left child, 24 — the answer is 4, between 24 and 20.

input
root: a binary search tree, written as on LeetCode: its values level by level, left to right, null for a missing child. Every value in a node's left subtree is smaller than the node's, every one in its right subtree greater.
returns
The smallest difference between the values of any two different nodes, not only a parent and its child.
constraints
  • 2 ≤ the number of nodes ≤ 10⁴
  • 0 ≤ Node.val ≤ 10⁵
  • the tree is a binary search tree, its values distinct
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
function getMinimumDifference(root) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more tree traversals problems

Pattern “Tree traversals” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.