题解 | #二叉搜索树最小差值#
二叉搜索树最小差值
http://www.nowcoder.com/practice/f8ac976b49bd450887b9281f315186c7
public class Solution {
public int minDifference (TreeNode root) {
List<Integer> list = new ArrayList<>();
// 首先进行中序遍历,二叉搜索树中序遍历的结果是单调递增的
inOrder(root, list);
int len = list.size();
int[] nums = new int[len - 1];
// 计算出所有差值
for (int i = 1; i < len; i++) {
nums[i - 1] = list.get(i) - list.get(i - 1);
}
Arrays.sort(nums);
return nums[0];
}
private void inOrder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inOrder(root.left, list);
list.add(root.val);
inOrder(root.right, list);
}
}