我专门讲的代码函数是getCount()。还有其他几个我没有在这里包含的函数(例如查找此二叉树的高度和总节点数),它们工作得很好,结果正确。另一方面,getCount() 会产生分段错误,但第一个节点(树的顶部,第一个节点)除外。有任何想法吗?
#include <string>
#include <algorithm>
#include <iostream>
class Word {
public:
std::string keyval;
long long count;
Word() {
keyval = "";
count = 0;
}
Word(std::string S) {
keyval = S;
count = 1;
}
};
class WordBST {
public:
Word node;
WordBST* left_child;
WordBST* right_child;
WordBST(std::string key);
void add(std::string key){
if (key == node.keyval){
node.count++;
}
else if (key < node.keyval){
if (left_child == NULL){
left_child = new WordBST(key);
}else {
left_child->add(key);
}
}else {
if (right_child == NULL){
right_child = new WordBST(key);
}else {
right_child->add(key);
}
}
}
long long getCount(std::string key){
if (key == node.keyval){
return (node.count);
}
else if (key < node.keyval){
left_child->getCount(key);
}else if(key > node.keyval){
right_child->getCount(key);
}else return 0;
/*else {
if (key < node.keyval){
left_child->getCount(key);
}else{
right_child->getCount(key);
}
}*/
}
};
WordBST::WordBST(std::string key) {
node = Word(key);
left_child = NULL;
right_child = NULL;
}