gpt4 book ai didi

java二叉树插入函数非递归

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:42 26 4
gpt4 key购买 nike

我编写了一个代码,用于将元素泛型类型插入二叉树,该类型按其名称排序。但不认为这是正确的。

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;
}

关于java二叉树插入函数非递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12767564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com