783. 二叉搜索树节点最小距离
- 注意这里是任意两个节点,不是相邻!
- 因为是二叉搜索树的原因,我们可以通过BFS获得递增序列
class Solution {
public int minDiffInBST(TreeNode root) {
dfs(root);
return 1;
}
// 左中右
public void dfs(TreeNode root){
if(root==null)
return;
dfs(root.left);
System.out.println(root.val);
dfs(root.right);
}
}
又因为我们最后的解一定是所有相邻两数差之间最小的,因此最终代码为:
class Solution {
int lastNum = -1; // 因为输入的值在[0,10^5之间]
int res = 100000;
public int minDiffInBST(TreeNode root) {
dfs(root);
return res;
}
// 左中右
public void dfs(TreeNode root){
if(root==null)
return;
dfs(root.left);
// 如果读取的是第一个数
if(lastNum==-1)
lastNum = root.val;
else{
res = Math.min(res,root.val - lastNum);
lastNum = root.val;
}
dfs(root.right);
}
}