Minimum Absolute Difference in BST - Problem

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

The absolute difference between two values a and b is |a - b|, which is always non-negative.

A BST is a binary tree where for every node, all values in the left subtree are smaller and all values in the right subtree are larger than the node's value.

Input & Output

Example 1 — Basic BST
$ Input: root = [4,2,6,1,3]
Output: 1
💡 Note: In-order traversal gives [1,2,3,4,6]. Adjacent differences are: |2-1|=1, |3-2|=1, |4-3|=1, |6-4|=2. Minimum is 1.
Example 2 — Larger Differences
$ Input: root = [1,0,48,null,null,12,49]
Output: 1
💡 Note: In-order traversal: [0,1,12,48,49]. Differences: |1-0|=1, |12-1|=11, |48-12|=36, |49-48|=1. Minimum is 1.
Example 3 — Single Node
$ Input: root = [1]
Output: 0
💡 Note: Only one node, so no pairs exist. Return 0 by convention.

Constraints

  • The number of nodes in the tree is in the range [2, 104]
  • 0 ≤ Node.val ≤ 105

Visualization

Tap to expand
BST INPUT42613Binary Search TreeLeft < Root < RightIN-ORDER TRAVERSAL1Step 12Step 23Step 34Step 46Step 5Adjacent Differences:|2 - 1| = 1|3 - 2| = 1|4 - 3| = 1|6 - 4| = 2FINAL RESULT1Min DiffMinimum absolutedifference foundbetween adjacentnodes in BSTKey Insight:In a BST, the minimum absolute difference always occurs between consecutive nodesin the in-order traversal (sorted order). One pass through the tree is sufficient.TutorialsPoint - Minimum Absolute Difference in BST | DFS In-Order Traversal
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 18
125.0K Views
Medium Frequency
~15 min Avg. Time
2.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen