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);
}
}
判断二叉树是否是完全的BST(java)
最新推荐文章于 2022-07-09 17:03:22 发布