98、验证是否是一个BST
给一个根结点,验证这个树是否是一个BST。
两种方法:
- 中序遍历一遍,看每一个数是否比后一个数大
- 前序遍历二叉树,如果当前结点比所有左边结点大,比右边节点小就返回true,关键点在于记录每个结点的左界限和右界限
//第一种方法
Integer last = null;
Boolean res = true;
public boolean isValidBST(TreeNode root) {
help(root);
return res;
}
public void help(TreeNode root) {
if (root != null) {
help(root.left);
if (last != null) {
if (root.val <= last)
res = false;
}
last = root.val;
help(root.right);
}
}
//第二种方法
public boolean isValidBST(TreeNode root) {
return method2(root, null, null);
}
public boolean method2(TreeNode root, TreeNode lower, TreeNode upper) {
if (root == null) return true;
if (lower != null && root.val <= lower.val) return false;
if (upper != null && root.val >= upper.val) return false;
//遍历左子树时将当前结点作为左子树的右界限
//遍历右子树时将当前结点作为右子树的左界限
return method2(root.left, lower, root) && method2(root.right, root, upper);
}
530、在BST中找到绝对差最小的两个结点的绝对差
因为中序遍历是一个有序数组,所以只要中序遍历一遍,记录每两个相邻元素的差值中最小的那个就ok:
public int getMinimumDifference(TreeNode root) {
help(root);
return minDiff;
}
Integer last = null;
int minDiff = Integer.MAX_VALUE;
public void help(TreeNode root) {
if (root != null) {
help(root.left);
if (last != null)
minDiff = Math.min(root.val - last, minDiff);
last = root.val;
help((root.right));
}
}