给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
示例 1:
输入:root = [4,2,6,1,3]
输出:1
示例 2:
输入:root = [1,0,48,null,null,12,49]
输出:1
提示:
- 树中节点数目在范围 [2, 100] 内
- 0 <= Node.val <= 10^5
- 差值是一个正数,其数值等于两值之差的绝对值
解答
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int getMinimumDifference(TreeNode root) {
inOrderMinDiff(root);
int minAbs = inOrderList.get(1)-inOrderList.get(0);
for (int i = 1; i < inOrderList.size()-1; i++)
minAbs = Math.min(minAbs, inOrderList.get(i+1)-inOrderList.get(i));
return minAbs;
}
List<Integer> inOrderList = new ArrayList<>();
// 通过中序遍历,得到元素单增的序列
public void inOrderMinDiff(TreeNode node) {
if (node == null) return;
inOrderMinDiff(node.left);
inOrderList.add(node.val);
inOrderMinDiff(node.right);
}
}