Cover image for Interview Classic 150 Questions P530 Minimum Absolute Difference in BST

Interview Classic 150 Questions P530 Minimum Absolute Difference in BST


Timeline

Timeline

2025-10-31

init

Inorder traversal

Problem:

The in-order traversal of a binary search tree is a sorted sequence, so we only need to compare adjacent values during in-order traversal.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
struct TreeNode {	int val;	TreeNode *left;	TreeNode *right;	TreeNode()		: val(0)		, left(nullptr)		, right(nullptr)	{	}	TreeNode(int x)		: val(x)		, left(nullptr)		, right(nullptr)	{	}	TreeNode(int x, TreeNode *left, TreeNode *right)		: val(x)		, left(left)		, right(right)	{	}};#include <stack>#include <algorithm>#include <climits>#include <cmath>using std::stack;class Solution {    public:	int getMinimumDifference(TreeNode *root)	{ 		// For a binary search tree, in-order traversal is in sorted order.		stack<TreeNode *> st;		TreeNode *p = root, *left, *right;		int res = INT_MAX, last = INT_MAX;		while (p || !st.empty()) {			if (p) {				st.push(p);				p = p->left;			} else {			    	// visit				p = st.top();				st.pop();				res = std::min(res, std::abs(last - p->val));				last = p->val;				p = p->right;			}		}		return res;	}};
Loading comments…