Problem:
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.
Explanation:
找到二叉搜索树结点的最小差值。
My Thinking:
My Solution:
Optimum Thinking:
由于是搜索二叉树,使用中序遍历能得到有序的数组,最小值一定是相邻的两个结点之差。
Optimum Solution:
class Solution {
Integer res = Integer.MAX_VALUE, pre = null;
public int minDiffInBST(TreeNode root) {
if (root.left != null)
minDiffInBST(root.left);
if (pre != null)
res = Math.min(res, root.val - pre);
pre = root.val;
if (root.right != null)
minDiffInBST(root.right);
return res;
}
}