检查BT是否为BST,且T扩展可比<;T>;JAVA
检查是BT是BST很简单,但我在使用类似类的时候正在努力使用算法 首先,我给出了BT的插入方法:检查BT是否为BST,且T扩展可比<;T>;JAVA,java,binary-search-tree,Java,Binary Search Tree,检查是BT是BST很简单,但我在使用类似类的时候正在努力使用算法 首先,我给出了BT的插入方法: public void insert(T item){ //initialize new BT and sets left, right, parent and data to null BinaryTree<T> newNode = new BinaryTree<T>(); newNode.setData(item); if (size==
public void insert(T item){
//initialize new BT and sets left, right, parent and data to null
BinaryTree<T> newNode = new BinaryTree<T>();
newNode.setData(item);
if (size==0){
tree = newNode;
size++;
return;
}
BinaryTree<T> t = tree;
boolean done = false;
while (!done){
int c = item.compareTo(t.getData());
if (c==0){
System.out.println("Duplicate key. Can't insert");
return;
}
//need to go left
else if (c<0){
//place to insert found
if (t.getLeft()==null){
t.setLeft(newNode);
newNode.setParent(t);
size++;
done = true;
}
else
//otherwise go left one branch
t = t.getLeft();
}
//c>0; need to go right
else{
//place to insert found
if (t.getRight()==null){
t.setRight(newNode);
newNode.setParent(t);
size++;
done=true;
}
else
t = t.getRight();
}
}
}
公共作废插入(T项){
//初始化新BT并将左、右、父项和数据设置为空
BinaryTree newNode=新的BinaryTree();
newNode.setData(项);
如果(大小==0){
tree=newNode;
大小++;
返回;
}
二叉树t=树;
布尔完成=假;
而(!完成){
int c=item.compareTo(t.getData());
如果(c==0){
System.out.println(“重复键。无法插入”);
返回;
}
//我需要向左走
否则,如果(c0;需要向右行驶
否则{
//找到要插入的位置
if(t.getRight()==null){
t、 setRight(newNode);
newNode.setParent(t);
大小++;
完成=正确;
}
其他的
t=t.getRight();
}
}
}
我在BT中插入了4 2 5 1 3,在BT中插入了1 2 3 4
这棵树看起来像:
4
/ \
2 5
/ \
1 3
1
\
2
\
3
\
4
4.
/ \
2 5
/ \
1 3
1.
\
2.
\
3.
\
4.
结果仍然返回true
对于BST的验证方法:
public static<T extends Comparable<T>> boolean isBinarySearchTree(BinaryTree<T> t){
if(t ==null){
return true;
}
if(t.getLeft()!=null && t.getLeft().getData().compareTo(t.getData())>0){
return false;
}
if(t.getRight() !=null && t.getRight().getData().compareTo(t.getData())<0){
return false;
}
return isBinarySearchTree(t.getLeft()) && isBinarySearchTree(t.getRight());
}
publicstaticbooleanisbarytree(binarytreet){
如果(t==null){
返回true;
}
如果(t.getLeft()!=null和&t.getLeft().getData().compareTo(t.getData())>0){
返回false;
}
如果(t.getRight()!=null&&t.getRight().getData().compareTo(t.getData())添加额外高度方法如何:
int height(BinaryTree bt) {
if (bt == null) {
return 0;
}
return 1 + Math.max(height(bt.getLeft()), height());
}
然后在isBinarySearchTree检查中添加额外的if语句:
if (height(t.getRight()) != height(t.getLeft())) {
return false;
}
这增加了O(logn)的复杂性,因为它可能在每一层上都贯穿树的高度。您的BinaryTree类已经在创建二进制搜索树。第二个示例也是BST。除非您想测试平衡BST?是的,我想我没有澄清我想测试平衡BST。这是我的错。