【发布时间】:2014-04-24 13:54:42
【问题描述】:
我需要制作一个程序来接受用户的数字,这些数字被解释为游戏的评级。该计划的重点是接受数字,并在质量而不是数量上制造不均衡的团队。
例如: 用户输入数字:25、50、63、80。
糟糕的团队将是:25、50。
好的团队应该是:63、90。
我使用的是二叉搜索树,所以时间是O(nlogn)。
到目前为止,我的代码接受数字,将它们放入树中,确定团队数量是否相等,但无法正确打印它们。我怀疑问题出在我的int main() 中,当我调用打印函数或实际打印函数时。
#include <iostream>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
node *createNode(int data) // creates nodes
{
node *newNode = NULL;
newNode = new node;
newNode->data=data;
newNode->left=NULL;
newNode->right=NULL;
return newNode;
}
node *insert(int data, node **tree) // inserts them into a tree
{
node *newNode=NULL;
if (*tree==NULL)
{
newNode = createNode(data);
*tree = newNode;
}
else if (data<(*tree)->data)
{
if ((*tree)->left==NULL)
{
newNode = createNode(data);
(*tree)->left=newNode;
}
else
{
newNode = insert(data, &((*tree)->left));
}
}
else
{
if ((*tree)->right==NULL)
{
newNode = createNode(data);
(*tree)->right = newNode;
}
else
newNode = insert(data, &((*tree)->right));
}
return newNode;
}
void destroy(node *tree) // destroy tree at the end
{
if (tree!=NULL)
{
if (tree->left!=NULL)
destroy(tree->left);
if (tree->right!=NULL)
destroy(tree->right);
delete tree;
}
}
int treeHeight(node *tree, int counter) // finds the height of the tree
{
if (tree==NULL) // if there is nothing in the tree, return 0
return counter;
int leftcount, rightcount; // leftcount counts the left side of the tree and right count counts the right side of the tree
counter++; // counter should go up by 1 for every node
rightcount = treeHeight(tree->right, counter); // searches the right side
leftcount = treeHeight(tree->left, counter); // searches the left side
if (rightcount > leftcount) // return the height
return rightcount;
else
return leftcount;
}
void printNode(node *Node)
{
if (Node!=NULL)
{
cout << Node->data << ", ";
}
}
void printLeft(node *tree)
{
if (tree!=NULL)
{
printLeft(tree->left);
printNode(tree);
}
}
void printRight(node *tree)
{
if (tree!=NULL)
{
printRight(tree->right);
printNode(tree);
}
}
int main()
{
node *root = NULL;
node *current = NULL;
int value;
while (true)
{
cout << "Enter a rating where the bigger the number, the better (zero to quit): ";
cin >> value;
if (value==0)
break;
current = insert(value, &root);
}
int height = treeHeight(root, 0); // call the function and display the height of the tree
if (height==0)
{
cout << "\nYou did not enter any players, the game cannot happen now. Thanks a lot." << endl;
return 0;
}
else if (height%2!=0)
{
cout << "Uneven amount of player, add one more player to make the teams equal in quantity" << endl;
cout << "Enter a rating: ";
cin >> value;
current = insert(value, &root);
}
cout << "\nThe bad team is: " ;
printLeft(root); // ???
cout << "\nThe good team is: ";
printRight(root); // ???
destroy(root);
return 0;
}
【问题讨论】:
标签: c++ tree nodes binary-search-tree