题目描述
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
解法一:暴力
将所有节点的 v a l val val 存到一个数组中。然后将数组进行排序,找到答案。将所有节点的 v a l val val 存入数组,可以使用 BFS 或者 DFS。
class Solution {
public int minDiffInBST(TreeNode root) {
List<Integer> list = new ArrayList<>();
// BFS
Deque<TreeNode> d = new ArrayDeque<>();
d.addLast(root);
while (!d.isEmpty()) {
TreeNode poll = d.pollFirst();
list.add(poll.val);
if (poll.left != null) d.addLast(poll.left);
if (poll.right != null) d.addLast(poll.right);
}
// DFS
// dfs(root, list);
Collections.sort(list);
int n = list.size();
int ans = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
int cur = Math.abs(list.get(i) - list.get(i - 1));
ans = Math.min(ans, cur);
}
return ans;
}
void dfs(TreeNode root, List<Integer> list) {
list.add(root.val);
if (root.left != null) dfs(root.left, list);
if (root.right != null) dfs(root.right, list);
}
}
时间复杂度:
O
(
n
×
log(n)
)
O(n \times \textit{log(n)})
O(n×log(n))
空间复杂度:
O
(
n
)
O(n)
O(n)
解法二:利用二叉搜索树的性质
二叉搜索树的中序遍历是有序的,因此我们可以直接对「二叉搜索树」进行中序遍历,保存遍历过程中的相邻元素最小值即是答案。
class Solution {
int pre;
int ans;
public int minDiffInBST(TreeNode root) {
ans = Integer.MAX_VALUE;
pre = -1;
dfs(root);
return ans;
}
public void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
if (pre == -1) {
pre = root.val;
} else {
ans = Math.min(ans, root.val - pre);
pre = root.val;
}
dfs(root.right);
}
}
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)