思路:
// @Title: 二叉搜索树节点最小距离 (Minimum Distance Between BST Nodes)
// @Author: qisiii
// @Date: 2024-09-16 15:43:41
// @Runtime: 1 ms
// @Memory: 40.3 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 minDiffInBST(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);
}
}