1.题目:
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
示例 1:
输入:root = [4,2,6,1,3] 输出:1
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/minimum-absolute-difference-in-bst 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.代码:
方法一:暴力!!
/**
* 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 getMinimumDifference(TreeNode root) {
List<Integer> result = new ArrayList<>();
preorder(root,result);
int max = Integer.MAX_VALUE;
for(int i=0; i<result.size(); i++){
for(int j=i+1; j<result.size();j++){
if(Math.abs(result.get(i)-result.get(j))<=max){
max=Math.abs(result.get(i)-result.get(j));
}
}
}
return max;
}
public void preorder(TreeNode root,List<Integer> result){
if(root==null) return;
result.add(root.val);
preorder(root.left,result);
preorder(root.right,result);
}
}
方法二:
边中序遍历,边用指针
/**
* 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 {
TreeNode pre = null;//用来记录前一个结点的值
int max = Integer.MAX_VALUE;//用来作比较,记录最小值
public int getMinimumDifference(TreeNode root) {
if(root==null) return 0;//注意这里也要返回,因为返回值是整数
inorderPlus(root);
return max;
}
public void inorderPlus(TreeNode root){
if(root==null) return;
inorderPlus(root.left);//左
if(pre!=null){//中
max=Math.min(max,Math.abs(root.val-pre.val));
}
pre=root;//移动指针
inorderPlus(root.right);//右
}
}