我特别谈到的代码函数是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;
}
答案 0 :(得分:2)
这是因为你让代码在没有命中return语句的情况下运行。
long long getCount(std::string key){
if (key == node.keyval){
return (node.count);
} else if (left_child && key < node.keyval){
return left_child->getCount(key); // Added return
} else if(right_child && key > node.keyval){
return right_child->getCount(key); // Added return
}
return 0;
}
您还需要在整个代码中的多个位置添加空值检查。您的add
方法包含它们,但getCount
没有。
答案 1 :(得分:2)
我认为你应该像这样编写getCount():
long long getCount(std::string key){
if (key == node.keyval){
return (node.count);
}
else if (key < node.keyval && left_child != NULL){
return left_child->getCount(key);
}else if(key > node.keyval && right_child != NULL){
return right_child->getCount(key);
}else return 0;
}
答案 2 :(得分:1)
在调用方法之前,不要检查节点的子节点是否存在。