Skip to main content
Back to problems
#783
Easy Algorithms

Minimum distance between bst nodes

Tree Depth-First Search Breadth-First Search Binary Search Tree Binary Tree
61.1% acceptance
Feb 27, 2026
3679
435
Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
/*
 * Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
 * Example 1:
 * Input: root = [4,2,6,1,3]
 * Output: 1
 * Example 2:
 * Input: root = [1,0,48,null,null,12,49]
 * Output: 1
 * Constraints:
 * The number of nodes in the tree is in the range [2, 100].
 * 0 <= Node.val <= 105
 * Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/
 */
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn min_diff_in_bst(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, prev: &mut Option<i32>, min_diff: &mut i32) {
      if let Some(n) = node {
        let b = n.borrow();
        dfs(&b.left, prev, min_diff);
        if let Some(p) = *prev {
          *min_diff = (*min_diff).min(b.val - p);
        }
        *prev = Some(b.val);
        dfs(&b.right, prev, min_diff);
      }
    }
    let mut prev = None;
    let mut min_diff = i32::MAX;
    dfs(&root, &mut prev, &mut min_diff);
    min_diff
  }
}