forked from rishabhgarg25699/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTree_Preorder_Postorder_Inorder.cpp
115 lines (101 loc) · 2.28 KB
/
BinaryTree_Preorder_Postorder_Inorder.cpp
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
// This program is to create a Binary Tree in C++ and then
// do Pre Order, Post Order and In order traversals of the Binary tree
// Code by Nishit Anand
#include<iostream>
using namespace std;
// Defining structure of elements of binary tree
struct node
{
int data;
struct node *left;
struct node *right;
};
// Function to create a new node of the binary tree
struct node* create_node(int key)
{
struct node* newnode= new node;
newnode->data=key;
newnode->left=NULL;
newnode->right=NULL;
return newnode;
}
// Function to insert an node in the binary tree
void insert_node(struct node*& root,struct node* node)
{
char a;
if(root==NULL)
{
root=node;
cout<<"Node Inserted\n";
}
else
{
cout<<"ENTER L OR R to insert in left or right of : "<<root->data<<" respectively : ";
cin>>a;
if(a=='L')
insert_node(root->left,node);
if(a=='R')
insert_node(root->right,node);
}
}
// Function for preorder traversal of Binary Tree
void preorder(struct node* root)
{
if(root)
{
cout<<" "<<root->data;
if(root->left)
preorder(root->left);
if(root->right)
preorder(root->right);
}
}
// Function for postorder traversal of Binary Tree
void postorder(struct node* root)
{
if(root)
{
if(root->left)
postorder(root->left);
if(root->right)
postorder(root->right);
cout<<" "<<root->data;
}
}
// Function for inorder traversal of Binary Tree
void inorder(struct node* root)
{
if(root)
{
if(root->left)
inorder(root->left);
cout<<" "<<root->data;
if(root->right)
inorder(root->right);
}
}
// Main function
int main()
{
struct node* root=NULL;
int value;
char b='y';
do
{
cout<<"\nEnter value to be inserted into Binary Tree:";
cin>>value;
insert_node(root,create_node(value));
cout<<"\nWANT TO ENTER MORE(y/n):";
cin>>b;
}
while(b=='y');
cout<<"PRE ORDER TRAVERSAL"<<endl;
preorder(root);
cout<<"\n";
cout<<"POST ORDER TRAVERSAL"<<endl;
postorder(root);
cout<<"\n";
cout<<"IN ORDER TRAVERSAL"<<endl;
inorder(root);
return 0;
}