Skip to main content
Back to problems
#530
Easy Algorithms

Minimum absolute difference in bst

Tree Depth-First Search Breadth-First Search Binary Search Tree Binary Tree
59.2% acceptance
Feb 19, 2026
4732
272
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
// 
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn get_minimum_difference(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    let mut prev = -1i32;
    let mut min_diff = i32::MAX;
    fn inorder(node: &Option<Rc<RefCell<TreeNode>>>, prev: &mut i32, min_diff: &mut i32) {
      if let Some(n) = node {
        let nb = n.borrow();
        inorder(&nb.left, prev, min_diff);
        if *prev >= 0 { *min_diff = (*min_diff).min(nb.val - *prev); }
        *prev = nb.val;
        inorder(&nb.right, prev, min_diff);
      }
    }
    inorder(&root, &mut prev, &mut min_diff);
    min_diff
  }
}