-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.cpp
More file actions
93 lines (89 loc) · 1.88 KB
/
BST.cpp
File metadata and controls
93 lines (89 loc) · 1.88 KB
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
#include <iostream>
#include<cstdlib>
#include <math.h>
#include<conio.h>
using namespace std;
//creating structure of a node
struct node {
int key;
struct node* left, *right;
};
/* function to create a new node of tree and r
eturns pointer */
struct node* newnode(int key)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->key = key;
temp->left = temp->right = NULL;
return temp;
};
/* Inorder traversal of a binary tree*/
void inorder(struct node* root)
{
if (root!=NULL)
{
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
/* postorder traversal of a binary tree*/
void postorder(struct node* root)
{
if (root!=NULL)
{
postorder(root->left);
postorder(root->right);
cout << root->key << " ";
}
}
void preorder(struct node* root)
{
if (root!=NULL)
{
cout <<root->key << " ";
preorder(root->left);
preorder(root->right);
}
}
//root is the address of node
struct node* insert(struct node* node,int key)
{
if (node==NULL)
{
return newnode(key);
}
if (key < node->key)
{
node->left = insert(node->left, key);
}
else if(key > node->key)
{
node->right = insert(node->right, key);
}
return node;
}
int main()
{
int size,x,y;
//struct node* originalroot;
struct node *root=NULL;
cout<<"Entre root value of tree";
cin>>y;
root = insert(root,y);
cout<<"enter tree size:"<<endl;
cin>>size;
cout<<"enter elements:"<<endl;
for(int i=1;i<size;i++)
{
cout<<"element "<<i+1<<"\n";
cin>>x;
insert(root, x);
}
inorder(root);
cout<<"\n";
preorder(root);
cout<<"\n";
postorder(root);
return 0;
}