给定二叉树的前序遍历,遍历是否是 BST
public static boolean isValid(int[] arr, int start, int end, int min, int max){
if (start > end){ // start > end:当前子树为空,返回 true,因为一个空树可以被视为 BST
return true;
}
int rootValue = arr[start];
if (rootValue < min || rootValue > max){ // 是否在范围中
return false;
}
int index = start;
while (index + 1 <= end && arr[index + 1] <= rootValue){
index++; // 截断点
}
boolean leftSubtree = isValid(arr, start + 1, index, min, rootValue - 1);
boolean rightSubtree = isValid(arr, index + 1, end, rootValue + 1, max);
return leftSubtree && rightSubtree;
}