[英]Counting the unique values in a binary search tree
我有一个二叉搜索树。 到目前为止,我已经能够使用中序遍历对树进行排序。 我的树是从文件中读取的字符串树,我想计算树中的所有唯一值(我需要将重复项用于代码的另一部分,所以我不能制作没有重复并计算)。 我需要遍历树来计算这些唯一值。
我认为如果对所有内容都进行了排序,那么计算唯一值会很容易,但我不确定我为什么会遇到问题。
此代码有效:
int uniqueCount(node* root, string c){
int count = 0;
if(root == NULL)
return 0;
else
if (root->word == c)
count++;
return 1 + uniqueCount(root->left, c) + uniqueCount(root->right, c);
}
但它计算了所有节点,包括我不想要的重复节点。
所以,我写了这个:
int uniqueCount(node* root, string c){
int counter = 0;
string found, temp = " ";
if (root == NULL){
counter = 0;
}
else{
if (c == root->word){
temp = c;
}
if(found != temp){
counter++;
found = temp;
}
}
return 1 + uniqueCount(root->left, c) + uniqueCount(root->right, c);
}
但是现在我的代码什么也没打印。
这是我的主要代码:
int main()
{
node *T;
ifstream fin;
string c;
int counter;
fin.open("C:\\Users\\owner\\Documents\\mytest.txt");
if(fin.fail())
{
cout << "Could not find your file. Shutting down.";
exit(1);
}
else{
T = NULL;
while(!fin.eof()){
if (c != " ")
bInsert (c, &T);
counter = uniqueCount(T, c);
fin >> c;
}
}
cout << "Number of distint words are: " << counter << endl;
cout << "In-order\n";
inOrder(T); cout << endl;
我将不胜感激任何帮助。
编辑:本学期到目前为止,我们学习的数据结构是堆栈、队列、列表,现在是二叉树。 所以对于这个项目,我只被允许使用这些数据结构。 我不会被允许使用 hash 表、地图或集合等。
如果你想计算二叉树的唯一内容,那么试试这个格式的代码
void uniquecount(struct Node* node)
{
int count=0;//make this global to bring value out of function
if (node == NULL)
return;
uniquecount(node->left);
if(node->right!=NULL && node->right==node->data)
count--;
else
count++;
uniquecount(node->right);
}
只要确保在创建二叉树时,如果父数据相等,则将节点插入到右侧。
如果您唯一关心的是计算文本中出现的唯一次数,请尝试以下操作:
int main()
{
string c;
ifstream fin;
set<string> unique_words;
fin.open("C:\\Users\\owner\\Documents\\mytest.txt");
if(fin.fail())
{
cout << "Could not find your file. Shutting down.";
exit(1);
}
else{
while(!fin.eof()){
fin>>c;
unique_words.insert(c);
}
int counter=unique_words.size();
cout << "Number of distint words are: " << counter << endl;
cout << "In-order\n";
for(auto a:unique_words)
cout<<a<<' '; //Use whatever separator you want
return 0;
}
这里的想法是set
容器实现了二叉树。 但不允许重复。 由于集合仅包含唯一值,因此唯一元素的数量不小于集合的大小。 如果您真的想保留副本,请使用multiset
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.