-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathBST.cpp
93 lines (88 loc) · 1.79 KB
/
BST.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
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (long int i=a;i<n;i++)
#define per(i,a,n) for (long int i=n-1;i>=a;i--)
#define pb push_back
typedef vector<long int> vi;
typedef long long int lli;
const lli mod=1000000007;
lli powmod(lli a,lli b) {lli res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
lli gcd(lli a,lli b) { return b?gcd(b,a%b):a;}
struct node
{
lli data;
node *left;
node *right;
};
node *createNode(lli val)
{
node *newNode=new node;
newNode->data=val;
newNode->left=NULL;
newNode->right=NULL;
return newNode;
}
void BST(node *&head,lli val)
{
node *temp=createNode(val);
node *curr=head;
node *parent=NULL;
while(curr!=NULL)
{
parent=curr;
if(val<=curr->data)
curr=curr->left;
else
curr=curr->right;
}
if(val<=parent->data)
parent->left=temp;
else
parent->right=temp;
}
void inorder(node *root)
{
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
void preorder(node *root)
{
if(root==NULL)
return;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
void postorder(node *root)
{
if(root==NULL)
return;
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
lli n;
cin>>n;
node *head;
rep(i,0,n)
{
lli val;
cin>>val;
if(i==0)
head=createNode(val);
else
BST(head,val);
}
cout<<"inorder"<<endl;
inorder(head);
cout<<"preorder"<<endl;
preorder(head);
cout<<"postorder"<<endl;
postorder(head);
}