判断二叉树是否是完全的BST(java)

在这里插入图片描述

import java.util.ArrayList;

public class 判断二叉树是否是完全的BST {
    private int preValue = Integer.MIN_VALUE;
    public  TreeNode create(){
        TreeNode t1 = new TreeNode(1,null,null);
        TreeNode t2 = new TreeNode(9,null,null);
        TreeNode t3 = new TreeNode(8,t1,t2);
        TreeNode t4 = new TreeNode(11,null,null);
        TreeNode t5 = new TreeNode(20,null,null);
        TreeNode t6 = new TreeNode(15,t4,t5);
        TreeNode t7 = new TreeNode(10,t3,t6);
        return  t7;
    }
    //中序遍历
public  void midprint(TreeNode root){

        if(root.left!=null)
            midprint(root.left);
        if(root!=null)
        System.out.print(root.data+" ");

        if (root.right!=null)
            midprint(root.right);
}
//以中序遍历为基础,进行递归判断
public boolean isBST(TreeNode root){
        if(root==null){
            return  true;
        }
    // 检查左子树,如果左子非bst(二叉查找树)立即返回false
    boolean isleft = isBST(root.left);
        if(isleft==false)
            return  false;
    // 如果根的值小于等于左子树的最大值,返回false
        if(root.data<=preValue)
            return false;
    // 更新最后访问的值,检查右子树
        preValue=root.data;
        //递归右子树
        isBST(root.right);

        return isleft;
}

    public static void main(String[] args) {
        判断二叉树是否是完全的BST bst = new 判断二叉树是否是完全的BST();
        TreeNode node = bst.create();
        bst.midprint(node);
        boolean bstBST = bst.isBST(node);
        System.out.println();
        System.out.println(bstBST);

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值