我目前正在尝试实现二进制搜索树,到目前为止,我遇到的唯一一个大问题是find()方法,因为我遇到了问题,当我正在寻找时,我没有得到任何答案一把钥匙,不在我的树上...... 到目前为止,这是我的代码:
public class Bst {
Node root;
Node head;
Node tail;
public Bst(){
root = null;
}
public void insert (Node root, int key){
Node newNode=new Node(key);
if(root==null){
root=newNode;
}
if(key<=root.getKey()){
if (root.getLeft()!=null){
insert(root.getLeft(), key);
}
else{
root.setLeft(newNode);
}
}
if (key>=root.getKey()){
if (root.getRight()!=null){
insert(root.getRight(),key);
}
else{
root.setRight(newNode);
}
}
}
public void printTree(Node root){
if (root==null) return;
printTree(root.getLeft());
System.out.print(root.getKey() + " ");
printTree(root.getRight());
}
public Node treeToCDLL(Node root){
if (root == null){
return null;
}
Node leftTree=treeToCDLL(root.getLeft());
Node rightTree=treeToCDLL(root.getRight());
if (leftTree == null){
head=root;
}
else {
head=leftTree;
leftTree.getLeft().setRight(root);
root.setLeft(leftTree.getLeft());
}
if (rightTree==null){
head.setLeft(root);
root.setRight(head);
tail=root;
}
else{
tail=rightTree.getLeft();
head.setLeft(tail);
tail.setRight(head);
root.setRight(rightTree);
rightTree.setLeft(root);
}
return head;
}
public boolean find(Node root, int key){
Node current=root;
while(current!=null){
if(current.getKey()==key){
return true;
}
else if(current.getKey()>key){
current=current.getLeft();
}
else
current=current.getRight();
}
return false;
}
public void printList(Node head){
Node current = head;
while(current!=null){
System.out.print(current.getKey() + " ");
current=current.getRight();
if(current==head) break;
}
}
public static void main (String[]args){
Bst bst=new Bst();
Node root=new Node(4);
bst.insert(root, 2);
bst.insert(root, 1);
bst.insert(root, 3);
bst.insert(root, 5);
bst.insert(root, 6);
System.out.print("in-order traversal: ");
bst.printTree(root);
System.out.println();
System.out.print("circular doubly linked list: ");
Node head= bst.treeToCDLL(root);
bst.printList(head);
System.out.println();
System.out.print("Der gesuchte Knoten : " + bst.find(root,6));
}
}
如果你能帮助我,我会非常高兴,因为我尝试了很多方法,当我正在寻找存在于树中的密钥时,看起来我只能得到一个答案
答案 0 :(得分:1)
在拨打find()
之前,您正在将BST转换为循环双向链表。根据定义,除非您标记已访问的节点,否则将继续搜索(如果节点不存在),
答案 1 :(得分:0)
您的find()
方法看起来不错。我可以看到的一个问题是你通过调用
Node head= bst.treeToCDLL(root);
在致电find()
之前,这就是你的程序无限循环的原因。
在致电find(7)
之前尝试bst.treeTOCDLL(root)
,它会给你错误。