-
Notifications
You must be signed in to change notification settings - Fork 297
/
TraverseBinaryTree.cpp
97 lines (93 loc) · 1.56 KB
/
TraverseBinaryTree.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
#include<iostream>
#include<stdlib.h>
using namespace std;
struct st
{
int data;
struct st *left;
struct st *right;
};
struct st *root=NULL,*temp;
void insertElements();
void preorder(struct st *);
void inorder(struct st *);
void postorder(struct st *);
int main()
{
int ch;
while(1)
{
cout<<"\n 1.insert Elements \n 2.preorder \n 3.inorder \n 4.postorder \n5.exit";
cout<<"\n enter ur choice ";
cin>>ch;
switch(ch)
{
case 1:insertElements();break;
case 2:preorder(root);break;
case 3:inorder(root);break;
case 4:postorder(root);break;
case 5:exit(1);break;
default:cout<<"invalid operation";
}
}
}
void insertElements()
{
struct st *nc,*pNode;
int v;
cout<<"\n enter the value ";
cin>>v;
temp=new st;
temp->data=v;
temp->left=NULL;
temp->right=NULL;
if(root==NULL)
{
root=temp;
}
else
{
nc=root;
while(nc!=NULL)
{
pNode=nc;
if(v<nc->data)
nc=nc->left;
else
nc=nc->right;
}
if(v<pNode->data)
{
pNode->left=temp;
}
else
pNode->right=temp;
}
}
void preorder(struct st *temp)
{
if(temp!=NULL)
{
cout<<" "<<temp->data;
preorder(temp->left);
preorder(temp->right);
}
}
void inorder(struct st *temp)
{
if(temp!=NULL)
{
inorder(temp->left);
cout<<" "<<temp->data;
inorder(temp->right);
}
}
void postorder(struct st *temp)
{
if(temp!=NULL)
{
postorder(temp->left);
postorder(temp->right);
cout<<" "<<temp->data;
}
}