Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.

Example :

Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array. The given tree [4,2,6,1,3,null,null] is represented by the following diagram: 4
/ \
2 6
/ \
1 3 while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.

Note:

  1. The size of the BST will be between 2 and 100.
  2. The BST is always valid, each node's value is an integer, and each node's value is different.

这道题跟之前那道Minimum Absolute Difference in BST没有任何区别,解法完全可以共用,讲解也可以参见之前的帖子,这里就简略的说一下。第一种方法很直接,通过中序遍历按顺序从小到大将所有的结点值都存入到一个数组中,然后就遍历这个数组,找相邻的两个的差值最小的返回即可,参见代码如下:

解法一:

class Solution {
public:
int minDiffInBST(TreeNode* root) {
int res = INT_MAX;
vector<int> v;
helper(root, v);
for (int i = ; i < v.size(); ++i) {
res = min(res, v[i] - v[i - ]);
}
return res;
}
void helper(TreeNode* node, vector<int>& vals) {
if (!node) return;
helper(node->left, vals);
vals.push_back(node->val);
helper(node->right, vals);
}
};

我们可以优化上面解法的空间复杂度,并不记录所有的结点值,而是只记录之前的结点值,然后做差值更新结果res即可。

解法二:

class Solution {
public:
int minDiffInBST(TreeNode* root) {
int res = INT_MAX, pre = -;
helper(root, pre, res);
return res;
}
void helper(TreeNode* node, int& pre, int& res) {
if (!node) return;
helper(node->left, pre, res);
if (pre != -) res = min(res, node->val - pre);
pre = node->val;
helper(node->right, pre, res);
}
};

其实我们也不必非要用中序遍历不可,用先序遍历同样可以利用到BST的性质,我们带两个变量low和high来分别表示上下界,初始化为int的极值,然后我们在递归函数中,分别用上下界和当前节点值的绝对差来更新结果res,参见代码如下:

解法三:

class Solution {
public:
int minDiffInBST(TreeNode* root) {
int res = INT_MAX;
helper(root, INT_MIN, INT_MAX, res);
return res;
}
void helper(TreeNode* node, int low, int high, int& res) {
if (!node) return;
if (low != INT_MIN) res = min(res, node->val - low);
if (high != INT_MAX) res = min(res, high - node->val);
helper(node->left, low, node->val, res);
helper(node->right, node->val, high, res);
}
};

下面这种方法是解法一的迭代的写法,思路跟之前的解法没有什么区别,参见代码如下:

解法四:

class Solution {
public:
int minDiffInBST(TreeNode* root) {
int res = INT_MAX, pre = -;
stack<TreeNode*> st;
TreeNode* p = root;
while (!st.empty() || p) {
if (p) {
st.push(p);
p = p->left;
} else {
p = st.top(); st.pop();
if (pre != -) res = min(res, p->val - pre);
pre = p->val;
p = p->right;
}
}
return res;
}
};

类似题目:

Minimum Absolute Difference in BST

Binary Tree Inorder Traversal

参考资料:

https://leetcode.com/problems/minimum-distance-between-bst-nodes/solution/

https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/114834/Inorder-Traversal-O(N)-time-Recursion-C++JavaPython

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Minimum Distance Between BST Nodes 二叉搜索树中结点的最小距离的更多相关文章

  1. Leetcode783.Minimum Distance Between BST Nodes二叉搜索树结点最小距离

    给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值. 示例: 输入: root = [4,2,6,1,3,null,null] 输出: 1 解释: 注意,root是树结点对象(Tr ...

  2. [LeetCode] Inorder Successor in BST II 二叉搜索树中的中序后继节点之二

    Given a binary search tree and a node in it, find the in-order successor of that node in the BST. Th ...

  3. [LeetCode] Delete Node in a BST 删除二叉搜索树中的节点

    Given a root node reference of a BST and a key, delete the node with the given key in the BST. Retur ...

  4. [LeetCode] 450. Delete Node in a BST 删除二叉搜索树中的节点

    Given a root node reference of a BST and a key, delete the node with the given key in the BST. Retur ...

  5. LeetCode 530. Minimum Absolute Difference in BST (二叉搜索树中最小绝对差)

    Given a binary search tree with non-negative values, find the minimum absolute difference between va ...

  6. 450 Delete Node in a BST 删除二叉搜索树中的结点

    详见:https://leetcode.com/problems/delete-node-in-a-bst/description/ C++: /** * Definition for a binar ...

  7. LeetCode 783. 二叉搜索树结点最小距离(Minimum Distance Between BST Nodes)

    783. 二叉搜索树结点最小距离 LeetCode783. Minimum Distance Between BST Nodes 题目描述 给定一个二叉搜索树的根结点 root, 返回树中任意两节点的 ...

  8. LeetCode 230. 二叉搜索树中第K小的元素(Kth Smallest Element in a BST)

    230. 二叉搜索树中第K小的元素 230. Kth Smallest Element in a BST 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的 ...

  9. 【Leetcode_easy】783. Minimum Distance Between BST Nodes

    problem 783. Minimum Distance Between BST Nodes 参考 1. Leetcode_easy_783. Minimum Distance Between BS ...

随机推荐

  1. SpringBoot系列: 使用 Swagger 生成 API 文档

    SpringBoot非常适合开发 Restful API程序, 我们都知道为API文档非常重要, 但要维护好难度也很大, 原因有: 1. API文档如何能被方便地找到? 以文件的形式编写API文档都有 ...

  2. 轴对称 Navier-Stokes 方程组的一个点态正则性准则

    对轴对称 NSE, 我们改进了 [Pan, Xinghong. A regularity condition of 3d axisymmetric Navier-Stokes equations. A ...

  3. 用juery的ajax方法调用aspx.cs页面中的webmethod方法

    首先在 aspx.cs文件里建一个公开的静态方法,然后加上WebMethod属性. 如: [WebMethod] public static string GetUserName() { //.... ...

  4. 两个Html页面之间值得传递

    传值的页面:<a href='stockProductInfo.html?prdId="+v.prdID+"' target='_blank'></html> ...

  5. 设计模式九: 观察者模式(Observer Pattern)

    简介 观察者属于行为型模式的一种, 又叫发布-订阅模式. 如果一个对象的状态发生改变,依赖他的对象都将发生变化, 那么这种情况就适合使用观察者模式. 它包含两个术语,主题(Subject),观察者(O ...

  6. LeetCode第十四题-字符串数组中最长的共同前缀

    Longest Common Prefix 问题简介: 编写一个函数来查找字符串数组中最长的公共前缀字符串,如果没有公共前缀,则返回空字符串"" 举例: 1: 输入: [“xwq” ...

  7. 20155312 张竞予 Exp4 恶意代码分析

    Exp4 恶意代码分析 目录 基础问题回答 (1)如果在工作中怀疑一台主机上有恶意代码,但只是猜想,所有想监控下系统一天天的到底在干些什么.请设计下你想监控的操作有哪些,用什么方法来监控. (2)如果 ...

  8. python加密

    ""#line:4 __all__ =[]#line:6 class OO0O0O000O0O0O000 :#line:8 ""#line:9 def __in ...

  9. python 学习第四天

    2.5列表list. 列表是python中的基础数据类型之一,其他语言中也有类似于列表的数据类型,比如js中叫数组,他是以[]括起来,每个元素以逗号隔开,而且他里面可以存放各种数据类型比如: li = ...

  10. redis-string操作

    操作之String操作 String操作,redis中的String在在内存中按照一个name对应一个value来存储.如图: set(name, value,ex=None,px=None,nx=F ...