搜索二叉树定义: 每一颗子树,左树都比节点小,右树都比节点大,无重复值。
中序遍历
依次递增就行
public static Integer preValue = Integer.MIN_VALUE;
public static boolean isBst(Node head){
if(head == null){
return true;
}
// 先遍历左子树
boolean isLeftBst = isBst(head.left);
if(!isLeftBst){
return false;
}
// 处理当前节点
if(head.value <= preValue){
//如果当前节点大于前一个值,就return false;
return false;
}else{
preValue = head.value; //更新preValue
}
//处理右子树
boolean isRightBst = isBst(head.right);
return isRightBst;
}
还有一种就是,中序遍历保存在数组中,然后for循环比较。
非递归方式
public static boolean isBstUnRecur(Node head) {
if (head == null) {
return true;
}
Stack<Node> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty() || head != null) {
if (head.left != null) {
stack.push(head.left);
head = head.left;
} else {
head = stack.pop();
if (head.value <= preValue) {
return false;
} else {
preValue = head.value;
}
head = head.right;
}
}
return true;
}

浙公网安备 33010602011771号