思路:
// @Title: 二叉搜索树的最小绝对差 (Minimum Absolute Difference in BST)
// @Author: qisiii
// @Date: 2024-09-16 15:42:45
// @Runtime: 1 ms
// @Memory: 43.2 MB
// @comment:
// @flag:
/**
* 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> list=new ArrayList<>();
dfs(root,list);
int result=list.get(1)-list.get(0);
for(int i=2;i<list.size();i++){
result=Math.min(result,list.get(i)-list.get(i-1));
}
return result;
}
private void dfs(TreeNode root,List<Integer> list){
if(root==null){
return;
}
dfs(root.left,list);
list.add(root.val);
dfs(root.right,list);
}
}