版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26440803/article/details/81348410
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.
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.
题目大意:找到二叉搜索树中任意两节点之差最小。
分析:由二叉搜索树的特性可知,每个节点的左子树 < 根节点 < 右节点 ,根据此特性我们知道,差值最小一定会出现在相邻的两个节点,也就是当前遍历到的节点与其左子树,右子树差值中的最小值。因此我们可以利用中序遍历求解。
代码:
class Solution {
Integer prev= null;
Integer res = Integer.MAX_VALUE;
public int minDiffInBST(TreeNode root) {
inOrder(root);
return res;
}
private void inOrder(TreeNode root){
if(root == null) return ;
inOrder(root.left);
if(prev!= null){
res = Math.min(res,root.val-prev);
}
prev = root.val;
inOrder(root.right);
}
}