Java---Judge whether a tree is a binary search tree BST

Java—Determine whether a tree is a binary search tree BST

Idea : For a binary tree, the simplest method is to traverse in order to see if it is an increasing sequence. If it is, it is a binary search tree. If it is not, it is not a binary search tree. Here a lastVisit is used to record the last searched node. This process is to first find the node in the bottom left corner, update lastVisit to the value of this node, and then update it in turn according to the middle order traversal.

Code:

/**
 * @Author shall潇
 * @Date 2021/3/4
 * @Description 
 */
public class BinaryTree {
    private static int lastVisit = Integer.MIN_VALUE;
    public static boolean isBST(Node root){
        if(root==null)return true;              //空树也是BST

        boolean judgeleft = isBST(root.left);   //判断左子树是否是

        if(root.date >= lastVisit && judgeleft){ //当前节点比上次访问的节点的数大
            lastVisit = root.date;
        }else {
            return false;
        }
        boolean judegright = isBST(root.right);//判断右子树是否是
        return judegright;
    }

    class Node{		//创建树的数据结构
        int date;   //节点数据
        Node left;  //左节点
        Node right; //有节点
    }
}

Guess you like

Origin blog.csdn.net/qq_43288259/article/details/114376008