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
|
#include <iostream>
using namespace std;
struct node
{
int key;
node* left = NULL;
node* right = NULL;
};
node* insert (node* tree, int key)
{
if (!tree)
{
node* new_tree = new node;
new_tree->key = key;
return new_tree;
}
else if (key < tree->key)
tree->left = insert (tree->left, key);
else
tree->right = insert (tree->right, key);
}
int Check (node* tree, node* left, node* right, int status)
{
if (!tree)
return status;
if (left) // this lines are for checking if the left child is the way it s supposed to be. If it is,
{ // we change/keep the status value at 1. Otherwise we set it at 2 and return it.
if(left->key < tree->key)
status = 1;
else
{
status = 2;
return status;
}
}
if (right) // this lines are for checking if the right child is the way it s supposed to be. If it is,
{ // we change/keep the status value at 1. Otherwise we set it at 2 and return it.
if(right->key > tree->key)
status = 1;
else
{
status = 2;
return status;
}
}
status = Check (tree->left, left->left, left->left, status); // We call this recursive function to do the
//same check on the entire left sub-tree
if (status != 2)// in order not to ever change a virtual status which has changed to 2.
{
status= Check (tree->right, right->left, right->right, status);// We call this recursive function to do the
//same check on the entire left sub-tree
}
return status;
}
void Delete (node* tree)
{
if (!tree)
return;
Delete(tree->left);
Delete(tree->right);
delete tree;
}
int main ()
{
node* tree = NULL;
int key;
int status = 0;
int input;
cout<<"1. Insert value \n2. Check if the tree's well structured \n3. Quit"<<endl;
cin >> input;
while (input == 1 || input == 2)
{
switch (input)
{
case 1:
cout<<"Digit the value you want to insert \n";
cin >> key;
tree = insert(tree, key);
break;
case 2:
status = Check (tree, tree->left, tree->right, status);
if (status == 1)
cout<<"Your tree's ok... BITCH \n";
else if (status == 2)
cout<<"Your tree's a shit \n";
break;
}
cout<<"1. Insert value \n2. Check if the tree's well structured \n3. Quit"<<endl;
cin >> input;
}
Delete(tree);
}
|