LeetCode 530. Minimum Absolute Difference in BST
考点 | 难度 |
---|---|
Tree | Easy |
题目
Given the root
of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
思路
用inorder把数字从小到大排列,依次算left和right的minimum difference。
答案
class Solution {
int min = Integer.MAX_VALUE;
Integer prev = null;
public int getMinimumDifference(TreeNode root) {
if (root == null) return min;
getMinimumDifference(root.left);
if (prev != null) {
min = Math.min(min, root.val - prev);
}
prev = root.val;
getMinimumDifference(root.right);
return min;
}
}