TheAlgorithms-C-Plus-Plus/data_structure/Tree.cpp

139 lines
2.5 KiB
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2019-08-27 23:14:38 +08:00
#include <list>
2017-12-24 01:30:49 +08:00
using namespace std;
struct node
{
2019-08-27 23:33:04 +08:00
int val;
node *left;
node *right;
2017-12-24 01:30:49 +08:00
};
void CreateTree(node *curr, node *n, int x, char pos)
{
2019-08-27 23:33:04 +08:00
if (n != NULL)
{
char ch;
cout << "\nLeft or Right of " << n->val << " : ";
cin >> ch;
if (ch == 'l')
CreateTree(n, n->left, x, ch);
else if (ch == 'r')
CreateTree(n, n->right, x, ch);
}
else
{
node *t = new node;
t->val = x;
t->left = NULL;
t->right = NULL;
if (pos == 'l')
{
curr->left = t;
}
else if (pos == 'r')
{
curr->right = t;
}
}
2017-12-24 01:30:49 +08:00
}
void BFT(node *n)
{
2019-08-27 23:14:38 +08:00
list<node*> queue;
queue.push_back(n);
while(!queue.empty())
{
n = queue.front();
cout << n->val << " ";
queue.pop_front();
if(n->left != NULL)
queue.push_back(n->left);
if(n->right != NULL)
queue.push_back(n->right);
}
2017-12-24 01:30:49 +08:00
}
void Pre(node *n)
{
2019-08-27 23:33:04 +08:00
if (n != NULL)
{
cout << n->val << " ";
Pre(n->left);
Pre(n->right);
}
2017-12-24 01:30:49 +08:00
}
void In(node *n)
{
2019-08-27 23:33:04 +08:00
if (n != NULL)
{
In(n->left);
cout << n->val << " ";
In(n->right);
}
2017-12-24 01:30:49 +08:00
}
void Post(node *n)
{
2019-08-27 23:33:04 +08:00
if (n != NULL)
{
Post(n->left);
Post(n->right);
cout << n->val << " ";
}
2017-12-24 01:30:49 +08:00
}
int main()
{
2019-08-27 23:33:04 +08:00
int value;
int ch;
node *root = new node;
cout << "\nEnter the value of root node :";
cin >> value;
root->val = value;
root->left = NULL;
root->right = NULL;
do
{
cout << "\n1. Insert";
2019-08-27 23:33:04 +08:00
cout << "\n2. Breadth First";
cout << "\n3. Preorder Depth First";
cout << "\n4. Inorder Depth First";
cout << "\n5. Postorder Depth First";
2019-08-21 10:10:08 +08:00
2019-08-27 23:33:04 +08:00
cout << "\nEnter Your Choice : ";
cin >> ch;
switch (ch)
{
case 1:
int x;
char pos;
cout << "\nEnter the value to be Inserted : ";
cin >> x;
cout << "\nLeft or Right of Root : ";
cin >> pos;
if (pos == 'l')
CreateTree(root, root->left, x, pos);
else if (pos == 'r')
CreateTree(root, root->right, x, pos);
break;
case 2:
BFT(root);
break;
case 3:
Pre(root);
break;
case 4:
In(root);
break;
case 5:
Post(root);
break;
}
} while (ch != 0);
2017-12-24 01:30:49 +08:00
}