做题博客链接
https://blog.youkuaiyun.com/qq_43349112/article/details/108542248
题目链接
https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/
描述
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
注意:本题与 530:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/ 相同
提示:
树中节点数目在范围 [2, 100] 内
0 <= Node.val <= 105
示例
示例 1:
输入:root = [4,2,6,1,3]
输出:1
示例 2:
输入:root = [1,0,48,null,null,12,49]
输出:1
初始代码模板
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDiffInBST(TreeNode root) {
}
}
代码
中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int prev;
private int res;
public int minDiffInBST(TreeNode root) {
this.prev = -100000;
this.res = 100000;
inOrder(root);
return res;
}
private void inOrder(TreeNode root) {
if (root == null){
return;
}
inOrder(root.left);
res = Math.min(res, root.val - prev);
prev = root.val;
inOrder(root.right);
}
}