Given a Binary Search Tree (BST) with the root node root
, return the minimum difference between the values of any two different nodes in the tree.
Example :
Input: root = [4,2,6,1,3,null,null] Output: 1 Explanation: Note that root is a TreeNode object, not an array. The given tree [4,2,6,1,3,null,null] is represented by the following diagram: 4 / \ 2 6 / \ 1 3 while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.
Note:
- The size of the BST will be between 2 and
100
. - The BST is always valid, each node's value is an integer, and each node's value is different.
根据题目可知,这是一颗BST树,BST树的特点就是中序遍历是有序的,题目要求任意两点只差的最小值,其实就是看BST中序遍历后相邻节点只差的绝对值的最小值。
程序如下所示:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
long min = Integer.MAX_VALUE, pre = Integer.MIN_VALUE;
public int minDiffInBST(TreeNode root) {
inOrder(root);
return (int)min;
}
public void inOrder(TreeNode root){
if (root != null){
inOrder(root.left);
min = Math.min(min, Math.abs(root.val - pre));
pre = root.val;
inOrder(root.right);
}
}
}