783. 二叉搜索树节点最小距离

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
int ans = Integer.MAX_VALUE;
List<Integer> list = new ArrayList<>();
public int minDiffInBST(TreeNode root) {
dfs(root);
for(int i = 1; i < list.size(); i++){
ans = Math.min(ans, list.get(i) - list.get(i-1));
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}

public void dfs(TreeNode root){
if(root == null){
return;
}

if(root.left != null){
dfs(root.left);
}

list.add(root.val);

if(root.right != null){
dfs(root.right);
}
}
}