名前と年齢を含む BST にノードを挿入することになっているこの挿入メソッドがあります。ツリー自体は年齢別にソートされ、各ノードにはその年齢の人々のリンクされたリストが含まれています。
このツリーの挿入方法は、これらのノードを互いに適切に比較していません。のような入力で
insert 1 50 john
insert 1 30 elvis
insert 1 90 david
insert 1 50 james
insert 1 95 abel
insert 1 80 esther
insert 1 95 vivian
insert 1 95 barbara
insert 1 50 james
James の重複挿入で挿入が失敗するのは 1 回だけです。代わりに、私のコードは 2 つの age 50 ノードを作成し、vivian の挿入に失敗するようです
Input Command: insert 1 50 john
Input Command: insert 1 30 elvis
Input Command: insert 1 90 david
Input Command: insert 1 50 james
Input Command: insert 1 95 abel
Input Command: insert 1 80 esther
Input Command: insert 1 95 vivian
--- Failed.
Input Command: insert 1 95 barbara
--- Failed.
Input Command: insert 1 50 james
なぜこれが起こっているのかわかりません。適切なタイミングで比較を実行しているようにも見えません。
いずれにせよ、ここに私のコードがあります
bool insert(const int &a, const string &n) {
BinaryNode* t = new BinaryNode;
BinaryNode* parent;
t->it = t->nameList.begin();
t->nameList.insert(t->it ,n);
t->age = a;
t->left = NULL;
t->right = NULL;
parent = NULL;
if(isEmpty()){
root = t;
return true;
}
else {
BinaryNode* curr;
curr = root;
while(curr) {
parent = curr;
if(t->age > curr->age)
curr = curr->right;
else
curr = curr->left;
}
if(t->age == parent->age) {
for(list<string>::iterator ti = parent->nameList.begin(); ti != parent->nameList.end(); ti++) {
string temp = *ti;
cout << temp << endl;
if(n.compare(temp))
return false;
else if(ti == parent->nameList.end())
parent->nameList.insert(ti,n);
}
return true;
}
if(t->age < parent->age) {
parent->left = t;
return true;
}
else {
parent->right = t;
return true;
}
}
}