判断是否是二叉搜索树

public class erchashoushuo {
    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode root;
        TreeNode(){};
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right){
            this.val = val;
            this.left = left;
            this.right = right;
        }


        public void setLeft(TreeNode left){
            this.left=left;
        }

        public void setRight(TreeNode right){
            this.right=right;
        }
        public void setRoot(TreeNode root){
            this.root=root;
        }

    }
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean isValidBST(TreeNode node, long lower, long upper) {
        if (node == null) {
            return true;
        }
        if (node.val <= lower || node.val >= upper) {
            return false;
        }
        return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper);
    }


    public static void main(String[] args) {
        TreeNode treeNode =new TreeNode();
        TreeNode node1=new TreeNode(1,null,null);
        TreeNode node2=new TreeNode(3,null,null);
        TreeNode root=new TreeNode(2, node1, node2);
        erchashoushuo er=new erchashoushuo();
        boolean k=er.isValidBST(root);
        System.out.println(k);
    }
}

全部评论

相关推荐

Hello_WordN:咱就是说,除了生命其他都是小事,希望面试官平安,希望各位平时也多注意安全
点赞 评论 收藏
分享
手撕没做出来是不是一定挂
Chrispp3:不会,写出来也不一定过
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务