请你说一下BST的特点,并手写代码判断一棵树是不是BST
参考回答:
1、每个结点都有一个作为搜索依据的关键码,所有结点的关键码不同
2、左子树上所有结点的关键码小于根节点的关键码
3、右子树所有结点的关键码大于根节点的关键码
4、左子树和右子树也是BST
判断一棵树是不是BST
class Node {
int data;
Node left;
Node right;
}
public class BSTChecker {
private static int lastVisit = Integer.MIN_VALUE;
public static boolean isBST(Node root) {
if(root == null) return true;
boolean judgeLeft = isBST(root.left); // 先判断左子树
if(root.data >= lastVisit && judgeLeft) { // 当前节点比上次访问的数值要大
lastVisit = root.data;
} else {
return false;
}
boolean judgeRight = isBST(root.right); // 后判断右子树
return judgeRight; } }