- 二叉搜索树节点最小距离:
https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/
1、首先抓住二叉搜索树的性质:二叉搜索树中序遍历得到的值序列是递增有序的。
2、采用二叉树中序遍历算法解题:
(1)递归
先采用中序遍历将读取的值存到数组中,然后依次比较两个相邻元素的差值,找到最小差值数后输出。
class Solution {
private:
vector<int> vec;
void dfs(TreeNode* root)
{
if(root == nullptr) return;
dfs(root->left); //递归遍历左子树
vec.push_back(root->val);
dfs(root->right);
}
public:
int minDiffInBST(TreeNode* root) {
vec.clear(); //清空元素,不回收空间
int ans=INT_MAX;
dfs(root);
if(vec.size()<2) return 0;
for(int i=1;i<vec.size();i++)
{
ans=min(ans,vec[i]-vec[i-1]);
}
return ans;
}
};
在遍历的过程中,首先将当前节点和前一节点进行比较,并记录当前最小差值,然后将当前节点视为前一节点,继续往下遍历完所有节点,最后返回最小差值。
class Solution {
public:
void dfs(TreeNode* root,int& pre,int& ans)
{
if(root == nullptr) return ;
dfs(root->left,pre,ans);
if(pre == -1) pre=root->val; //如果pre=-1,说明当前节点是根节点
else{
ans=min(ans,root->val-pre); //比较当前节点和前一节点
pre=root->val; //当前节点变为前一节点
}
dfs(root->right,pre,ans);
}
int minDiffInBST(TreeNode* root) {
int pre=-1,ans=INT_MAX;
dfs(root,pre,ans);
return ans;
}
};