LeetCode 783 Minimum Distance Between BST Nodes

题意

给予一颗二叉搜索树, 返回任意两个节点之间的最小相差值.

注: 树至少有两个节点.

例 :

1
2
3
4
5
6
7
8
9
10
11
给予树:


1
\
4
/ \
2 7


返回: 1 (1 和 2 之间相差 1).

解法

这道题很像: Minimum Absolute Difference in BST, 解法甚至可以通用.

因为是一颗二叉搜索树, 所以采用中序遍历可以得到所有值从小到大的排列, 那么将每个节点与上个节点的值 prev 进行比较得出相差值 answer, 判断相差值与上个相差值, 将更小的存起来. 直到遍历完整棵树.

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int prev = -1;
private int answer = Integer.MAX_VALUE;
public int minDiffInBST(TreeNode root) {
if (root.left != null) {
minDiffInBST(root.left);
}

if (prev != -1) {
answer = Math.min(answer, root.val - prev);
}

prev = root.val;

if (root.right != null) {
minDiffInBST(root.right);
}
return answer;
}
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Minimum Distance Between BST Nodes.
Memory Usage: 33.5 MB, less than 100.00% of Java online submissions for Minimum Distance Between BST Nodes.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-783/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!