题目描述:
给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
思路:
1)结合前面两道:二叉搜索树中的搜索和验证二叉搜索树!
可以看出BST的题目,一般都有 递归和 迭代的中序遍历两种!
需要记清楚怎么做!
代码:
1)递归
class Solution {
TreeNode pre;//用来记录前一个结点 很好用!
int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if(root == null) return 0;
min(root);
return res;
}
//第一个当前节点,一定是从 最左子树的 根节点开始!
void min(TreeNode root){
if(root == null) return;//走到底了
//没有走到底,就往左继续走
//左
min(root.left);
//中:也就是判断
//前一个节点肯定是小的!
if(pre != null){
res = Math.min(res,root.val - pre.val);
}
//判断之后将该点设置为当前节点,往右递归
pre = root;
min(root.right);
}
}
2)迭代:时间消耗较多
class Solution {
TreeNode pre;
Stack<TreeNode> stack;
public int getMinimumDifference(TreeNode root) {
if (root == null) return 0;
stack = new Stack<>();
TreeNode cur = root;
int result = Integer.MAX_VALUE;
while (cur != null || !stack.isEmpty()) {
//先将每个节点都走到最左!
while(cur != null) {
stack.push(cur); // 将访问的节点放进栈
cur = cur.left; // 左
}
cur = stack.pop();
if (pre != null) { // 中
result = Math.min(result, cur.val - pre.val);
}
pre = cur;
cur = cur.right; // 右
}
return result;
}
}