我正在研究Java
,我有一些问题:
这是binary search tree
,我想创建insert
方法。我做了什么错了?
我认为left
和right
是Node
,但我不知道如何使用它,因为Node
我知道就像
public Node(int data, Node next)
我该怎么做?
public class BST {
private Comparable key;
private BST left, right;
public BST(Comparable key) {
this.key = key;
this.left = null;
this.right = null;
}
public boolean insert(Comparable key) {
if (key.compareTo(this.key) < 0) {
if (this.left == null) {
System.out.println(key + " : insert success");
this.left = left;
return true;
} else {
insert(key);
}
} else if (key.compareTo(this.key) > 0) {
if (this.right == null) {
this.right = right;
System.out.println(key + " : insert success");
return true;
} else {
insert(key);
}
}
System.out.println(key + " : insert fail");
return false;
}
public static void main(String[] args) {
BST b = new BST("B");
System.out.println("========== insert ==========");
b.insert("G");
b.insert("D");
b.insert("K");
b.insert("A");
b.insert("D");
b.insert("J");
b.insert("H");
b.insert("C");
b.insert("A");
b.insert("F");
b.insert("E");
b.insert("N");
}
}
答案 0 :(得分:0)
you are not doing the insert correctly , when you find the position you need to create a new Node with the new key and make it the leaf, for example in your first check
if (key.compareTo(this.key) < 0) {
if (this.left == null) {
System.out.println(key + " : insert success");
this.left = new BST(key);
return true;
} else {
return insert(key);
}
you also need to check if the sent key is already inserted and return true.