我正在尝试实现一个字符二叉搜索树。我无法理解插入字符的逻辑。假设这段代码在主函数中:insert("a");
insert("b");
insert("c");
insert("d");
当会出现 a 小于 a 的情况吗?那么我的树岂不就是全部在右侧了吗?
a
\
b
\
c
\
d
这样做可以吗?因为永远不会有比a更小的字母。但是这种感觉不对,但我不确定我错了什么。
我的插入函数:
void insert(char letter, node * curr)
{
int count{0};
if ( strcmp(curr->getLetter(), letter) == 0)
return 0;
if (!curr->getRight() && strcmp(curr->getLetter(), letter) > 0)
{
curr->getRight() = new node(letter);
return 1;
}
if (!curr->getLeft() && strcmp(curr->getLetter(), letter) < 0)
{
curr->getLeft() = new node(letter);
return 1;
}
if (strcmp(letter, curr->getLetter() ) < 0)
count += insert(letter, curr->getLeft() );
else
count += insert(letter, curr->getRight() );
return count;
}
strcmp
works on strings (char*
), not singlechar
s. To compare chars use simply<
or>
:curr->getLetter() < letter
. Or, if you really want to do three way comparison, C++20 has spaceship operator:curr->getLetter() <=> letter < 0
- Yksisarvinenchar *
。但为了简单起见,我将其切换为 char。无论如何还是谢谢! - Ahmad Safa