-
Notifications
You must be signed in to change notification settings - Fork 3
/
BST_Max_Min.cpp
83 lines (77 loc) · 1.53 KB
/
BST_Max_Min.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
#include <iostream>
using namespace std;
struct Node{
int data;
Node* left;
Node* right;
};
int Min(Node *root){
if(root==NULL){
cout<<"Tree is empty\n";
return -1;
}
else if(root->left==NULL){
return root->data;
}
else{
return Min(root->left);
}
}
int Max(Node *root){
if(root==NULL){
cout<<"Tree is empty\n";
return -1;
}
else if(root->right==NULL){
return root->data;
}
else{
return Max(root->right);
}
}
void Print(Node* root){
if(root==NULL){
return ;
}
Print(root->left);
cout<<root->data<<" ";
Print(root->right);
}
Node* GetNewNode(int data){
Node* newNode=new Node();
newNode->data=data;
newNode->left=newNode->right=NULL;
return newNode;
}
Node* Insert(Node* root, int data){
if(root==NULL){
root=GetNewNode(data);
return root;
}
else if(data<=root->data)
root->left=Insert(root->left,data);
else
root->right=Insert(root->right,data);
return root;
}
int main()
{
int num;
Node* root=NULL;
root=Insert(root,15);
root=Insert(root,20);
root=Insert(root,10);
root=Insert(root,40);
root=Insert(root,5);
root=Insert(root,30);
root=Insert(root,76);
cout<<"The BST inorder traversal is:\n";
Print(root);
cout<<"\nThe minimum element of the BST is: ";
int x=Min(root);
cout<<x;
cout<<"\nThe maximum element of the BST is: ";
int y=Max(root);
cout<<y;
return 0;
}