借助中序遍历,元素会按照顺序输出的特点
package FTree;
/**
* @Author Zhou jian
* @Date 2020 ${month} 2020/4/14 0014 12:23
* 给你一棵所有节点为非负值的二叉搜索树,
* 请你计算树中任意两节点的差的绝对值的最小值。
*
*/
public class Problem530 {
//存放结果
int min = Integer.MAX_VALUE;
//当前元素的值
int cur = 0;
//当前元素的前一个节点的值(默认不存在)
int pre = -1;
//利用二叉树的中序遍历的特性,将问题转换为在升序排列的数中寻找相邻两数的差的最小额值
//用一个变量记录上一个数,每次只要计算当前数和上一个树的差,然后和最小值比较,并在比较后更新一个数即可
//中序遍历求 相邻数据之键的差值即可
public int getMinimumDifference(TreeNode root) {
if(root==null) return 0;
inOrder(root);
return min;
}
//中序遍历会按照顺序输出所有节点
public void inOrder(TreeNode root){
if(root==null) return;
inOrder(root.left);
//第一次求取
if(pre==-1){
pre=root.val;
}else{
int cur = root.val;
min = Math.min(min,Math.abs(cur-pre));
pre=cur;
}
inOrder(root.right);
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int min = Integer.MAX_VALUE;
int pre = -1;
public int minDiffInBST(TreeNode root){
dfs(root);
return min;
}
//中序遍历返回所有接地那
public void dfs(TreeNode root) {
//中序遍历
if (root == null) return;
dfs(root.left);
if(pre!=-1){
min = Math.min(min,root.val-pre);
}
pre=root.val;
dfs(root.right);
}
}