1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
#include <iostream>
#include <fstream>
#include <string>
#include "Windows.h"
using namespace std;
//Binary Tree Class
class BinarySearchTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
string softwareCode;
string softwareName;
string softwareVersion;
string softwarePrice;
};
tree_node* root;
public:
BinarySearchTree()
{
root = NULL;
}
bool isEmpty() const { return root==NULL; }
void print_inorder();
void inorder(tree_node*);
void insert(string, string, string, string);
void remove(string, string, string, string);
void write_node(tree_node*);
void writeToFile();
};
// Smaller elements go left
// larger elements go right
void BinarySearchTree::insert(string code, string name, string version, string price)
{
tree_node* t = new tree_node;
tree_node* parent;
t->softwareCode = code;
t->softwareName = name;
t->softwareVersion = version;
t->softwarePrice = price;
t->left = NULL;
t->right = NULL;
parent = NULL;
// is this a new tree?
if(isEmpty()) root = t;
else
{
//Note: ALL insertions are as leaf nodes
tree_node* curr;
curr = root;
// Find the Node's parent
while(curr)
{
parent = curr;
if(t->softwareCode > curr->softwareCode) curr = curr->right;
else curr = curr->left;
}
if(t->softwareCode < parent->softwareCode)
parent->left = t;
else
parent->right = t;
}
}
//print Tree in order
void BinarySearchTree::print_inorder()
{
inorder(root);
}
//sorting the tree
void BinarySearchTree::inorder(tree_node* p)
{
if(p != NULL)
{
if(p->left) inorder(p->left);
cout << "Software Code: " << p->softwareCode << endl;
cout << "Software Name: " << p->softwareName << endl;
cout << "Software Version: " << p->softwareVersion << endl;
cout << "Software Price: $" << p->softwarePrice << endl << endl;
if(p->right) inorder(p->right);
}
else return;
}
void BinarySearchTree::writeToFile()
{
write_node(root);
}
void BinarySearchTree::write_node(tree_node*p)
{
string code, name, version, price;
ofstream file("newsoftware.txt");
file.is_open();
if(p != NULL)
{
if(p->left) inorder(p->left);
file << p->softwareCode << endl;
file << p->softwareName << endl;
file << p->softwareVersion << endl;
file << p->softwarePrice << endl << endl;
if(p->right) inorder(p->right);
}
}
|