BINARY TREE IN-ORDER TRAVERSE, SEARCH KEY, MINIMUM ,MAXIMUM,
DELETE KEY
#include<iostream>
using namespace std;
class Tree {
public:
int data;
Tree* left;
Tree* right;
Tree(int a) {
data = a;
left = NULL;
right = NULL;
};
void DFS(Tree* root) {
if (root == NULL)
return;
DFS(root->left);
cout << root->data << " ";
DFS(root->right);
}
bool search(Tree* root, int key) {
if (root == NULL) {
return false;
else if (root->data == key) {
return true;
else if (root->data < key) {
return search(root->right, key);
else {
return search(root->left, key);
void min(Tree*root){
while(root->left!=NULL){
root=root->left;
cout<<"minimum is "<<root->data;
void max(Tree*root){
while(root->right!=NULL){
root=root->right;
}
cout<<"maximum is "<<root->data;
void deleteNode(Tree*& root, int key) {
if (root == NULL) {
return;
if (key < root->data) {
deleteNode(root->left, key);
else if (key > root->data) {
deleteNode(root->right, key);
else if(key==root->data) {
if (root->left == NULL && root->right == NULL) {
delete root;
root = NULL;
else if (root->left == NULL) {
Tree* temp = root->right;
delete root;
root = temp;
} else if (root->right == NULL) {
Tree* temp = root->left;
delete root;
root = temp;
}
else{
Tree* temp = root->right;
delete root;
root = temp;
int main() {
Tree* nodes[13];
nodes[1] = new Tree(6);
nodes[2] = new Tree(4);
nodes[3] = new Tree(11);
nodes[4] = new Tree(2);
nodes[5] = new Tree(5);
nodes[6] = new Tree(9);
nodes[7] = new Tree(12);
nodes[8] = new Tree(1);
nodes[9] = new Tree(3);
nodes[10] = new Tree(8);
nodes[11] = new Tree(10);
nodes[12] = new Tree(7);
nodes[1]->left = nodes[2];
nodes[1]->right = nodes[3];
nodes[2]->left = nodes[4];
nodes[2]->right = nodes[5];
nodes[4]->left = nodes[8];
nodes[4]->right = nodes[9];
nodes[3]->left = nodes[6];
nodes[3]->right = nodes[7];
nodes[6]->left = nodes[10];
nodes[6]->right = nodes[11];
nodes[10]->left = nodes[12];
cout << "DFS traversal: ";
DFS(nodes[1]);
cout << endl;
int key;
cout << "Enter key to search: ";
cin >> key;
if (search(nodes[1], key)) {
cout << "Found!" << endl;
} else {
cout << "Not Found!" << endl;
min(nodes[1]);
cout<<endl;
max(nodes[1]);
int a;
cout<<endl<<"enter key to delete: ";
cin>>a;
deleteNode(nodes[1],a);
cout<<endl;
cout << "DFS traversal: ";
DFS(nodes[1]);
cout << endl;
return 0;
Output: