试图向 BST 添加一个元素。我有一个想法,但是我的实现是破坏性的,并且没有保留原始根(因此树基本上变得无用)。树是基于列表的,这种方法是基于递归的。我真正的问题是保留原始根。我正在使用泛型。
到目前为止我所拥有的:
public void addElement(E elem, Node<E> root) {
创建一个值为 elem 的节点,命名为 newNode
案例1:树是空的
root = newNode();
return; //End of method.
否则,继续搜索树(通过将节点 a 的值与树的根进行比较。
if (!root.hasLeft() && !root.hasRight) { //if the root in question has no children
if (elem < rootValue) { //Set the element as the left element
root.setLeft(newNode);
}
else { //Set the element as the right element.
root.setRight(newNode);
}
}
else {
if (E < root.getElem()) {
//This is where the value of our node is compared to the value of the root, which we passed in.
//(I know that we can't use the < and > operators with generics, but assume it works).
root = root.getLeft() //Left node is new root
addElement(elem, root); //Call the method again
}
else {
root = root.getRight(); //Right node is new root
addElement(elem, root) //Call method again
}
}
}
如果这是一个重复/模糊的问题,请原谅我,这是我在 SO 上的第一篇文章,我有点菜鸟。