【leetcode】530题解

Minimum Absolute Difference in BST

  • 题目描述:

给定一棵二叉搜索树,计算两个节点之间差值的最小值

  • 样例:
1
2
3
4
5
6
7
8
9
10
Input:

1

3
/
2

Output:
1
  • 题解:

二叉搜索树的特点时左子树小于根,右子树大于根,所以当我们进行中序遍历时,就是一个升序的序列。所以这个题我们可以采用中序遍历的方法来进行解答。

  • code:
1
2
3
4
5
6
7
8
9
10
11
12
13
Integer pre = null;
public int (TreeNode root) {
if (root == null) {
return min;
}
getMinimumDifference1(root.left);
if (pre != null) {
min = Math.min(min, root.val - pre);
}
pre = root.val;
getMinimumDifference1(root.right);
return min;
}