Cover image for 面试经典150题 P530 二叉搜索树的最小绝对差

面试经典150题 P530 二叉搜索树的最小绝对差


时间轴

时间轴

2025-10-31

init

中序遍历

题目:

二叉搜索树的中序遍历是有序序列,因此只需要中序遍历比较邻近值大小即可

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)	{ 		// 二叉搜索树,中序遍历是按顺序排列的		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;	}};
评论加载中…