我正在尝试用双打来实现二叉树,但我相信我的双打比较是不正确的。当我用它喂它时它能正常工作;但是,如果我插入带有许多尾随小数位的双精度数,我会得到一个段错误。
这是我的插入功能:
int BinaryTree::insert_node(double val, char *str){;
return insert_node_helper(this->root, val, str);
}
int BinaryTree::insert_node_helper(TreeNode *&node, double val, char *str){
if(node == NULL){
node = new TreeNode;
node->val = val;
node->str = strdup(str);
node->left = NULL;
node->right = NULL;
return 0;
}else if(val > node->val){
return insert_node_helper(node->right, val, str);
}else{
return insert_node_helper(node->left, val, str);
}
return 1;
}
TreeNode定义:
struct TreeNode {
double val;
char *str;
TreeNode *left;
TreeNode *right;
};
致电代码:
void HashTable::chi_squared(){
int numTokens = numBigrams + 1;
BinaryTree topBigrams;
int treeInsertions = 0;
//indices for confusion matrix
int o11, o12, o21, o22 = 0;
int w1, w2, notW1, notW2 = 0;
double e11, e12, e21, e22 = 0;
double x2 = 0;
for(int i = 0; i < size; i++){
if(table[i] != NULL){
TokenList *temp = table[i]->tl;
while(temp != NULL){
Entry *temp2 = search(temp->str);
if(temp2 == NULL){
printf("string ( %s ) \n", temp->str);
temp = temp->next;
continue;
}
o11 = temp->occurrences; //total occurrences of word1 followed by word2
o21 = table[i]->occurrences - temp->occurrences; //total occurrences of word1 not followed by word2
o12 = search(temp->str)->occurrences - temp->occurrences; //total occurrences of not word1 followed by word2
o22 = numTokens - o11 - o12 - o21; //total occurrences of not word1 followed by not word2
w1 = table[i]->occurrences;
w2 = search(temp->str)->occurrences;
notW1 = numTokens - w1;
notW2 = numTokens - w2;
e11 = (w1 / (double)numTokens) * (w2 / (double)numTokens) * numTokens;
e12 = (notW1 / (double)numTokens) * (w2 / (double)numTokens) * numTokens;
e21 = (w1 / (double)numTokens) * (notW2 / (double)numTokens) * numTokens;
e22 = (notW1 / (double)numTokens) * (notW2 / (double)numTokens) * numTokens;
x2 = (pow((o11 - e11), 2) / (double)e11) +
(pow((o12 - e12), 2) / (double)e12) +
(pow((o21 - e21), 2) / (double)e21) +
(pow((o22 - e22), 2) / (double)e22);
x2 /= 100;
if(x2 >= 50){
if(treeInsertions < 100){
topBigrams.insert_node(x2, strcat(strcat(temp->str, " "), table[i]->str));
treeInsertions++;
}else if(x2 > topBigrams.find_min()->val){
topBigrams.replace_min(x2, strcat(strcat(temp->str, " "), table[i]->str));
}
temp = temp->next;
}
}
}
}
x2通常看起来像:50.91747014595311071616 但是,如果它是50或任何其他整数,插入工作正常。
我非常感谢任何帮助!