[英]Adding an element a binary search tree
試圖將元素添加到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帖子,我有點菜鳥。
if (!root.hasLeft() && !root.hasRight) {
這種邏輯是錯誤的。 如果您既沒有左孩子又沒有右孩子,則只考慮“設置”左孩子。 此更改應做到:
void addElement(elem, root)
{
if (elem < root.value) {
if(!root.hasLeft())
root.setLeft(newNode);
else
addElement(elem, root.getLeft());
}
else {
if(!root.hasRight())
root.setRight(newNode);
else
addElement(elem, root.getRight());
}
}
您不應更改類的根,而應將其傳遞給下一個方法調用。 這應該保留根。
順便說一句,我假設您在某個地方或類似地方有rootValue = root.value
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.