我写了一个代码,用于将元素泛型的类型插入到二叉树中,该类型按其名称排序。不过不要认为这是正确的。
public boolean insert(E e) {
BTNode temp = root;
if (root == null) {
root.setElement(e);
}
while (temp != null)
if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) {
temp = temp.getRight();
} else {
temp = temp.getLeft();
}
temp.setElement(e);
return true;
}
你能建议我更正吗?
插入需要创建一个新节点。我现在不知道如何创建它们,因为我还没有看到构造器,但我建议如下:
public boolean insert(E e) {
if (root == null) {
root = new BTNode();
root.setElement(e); //how would this work with a null root?
return true; //that's it, we're done (when is this ever false by the way?)
}
BTNode current = root;
while (true) { //brackets! indenting is important for readabilty
BTNode parent=current;
if (current.element().getClass().getName().compareTo(e.getClass().getName()) < 0) {
current = current.getRight();
if(current==null) { //we don't have a right node, need to make one
current = new BTNode();
parent.setRight(current);
break; //we have a new node in "current" that is empty
}
} else {
current= current.getLeft();
if(current==null) { //we don't have a left node, need to make one
current = new BTNode();
parent.setLeft(current);
break; //we have a new node in "current" that is empty
}
}
}
current.setElement(e);
return true;
}
public Boolean add(int data){
Node node = new Node(data);
if(isEmpty()){
root = node;
}else{
Node temp = root;
while(true){
if(data < temp.getData()){
if(temp.getLeft() != null)
temp = temp.getLeft();
else
break;
}else{
if(temp.getRight() != null)
temp = temp.getRight();
else
break;
}
}
if(data < temp.getData())
temp.setLeft(node);
else
temp.setRight(node);
}
return true;
}
正如 amadeus 所提到的,while 循环的末尾不应该有分号:
BTNode temp = root;
if (root == null) {
root.setElement(e);
return;
}
while (temp != null)
{
if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) {
if(temp.getRight() != null)
temp = temp.getRight();
else
{
temp.createRight(e);
temp = null; //or break
}
} else {
if(temp.getLeft() != null)
temp = temp.getLeft();
else
{
temp.createLeft(e);
temp = null; //or break
}
}
}
return true;