LC.P783[二叉搜索树节点最小距离]

方法一:遍历+排序

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
28
29
30
31
32
33
34
/**
* 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);
list.sort((a, b) -> a - b);
int ans = Integer.MAX_VALUE;
for (int i = 1; i < list.size(); ++i) {
ans = Math.min(ans, Math.abs(list.get(i - 1) - list.get(i)));
}
return ans;
}

private void dfs(TreeNode root, List<Integer> list) {
if (root == null) return;
list.add(root.val);
dfs(root.left, list);
dfs(root.right, list);
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$

方法二:中序遍历

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
28
29
30
31
32
33
34
/**
* 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 {
TreeNode pre = null;
int ans = Integer.MAX_VALUE;

public int minDiffInBST(TreeNode root) {
dfs(root);
return ans;
}

private void dfs(TreeNode root) {
if (root == null) return;
dfs(root.left);
if (pre != null) {
ans = Math.min(ans, Math.abs(root.val - pre.val));
}
pre = root;
dfs(root.right);
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$