You are on page 1of 4

#include<iostream>

using namespace std;

class Node
{
public:
Node *left;
Node *right;
int data;
} ;

class bt
{
private:
Node *root;
void insert(int item, Node* tree);
void inorder(Node* root);
Node* search(Node* tree,int num);
int min(Node* temp);
int max(Node* temp);
Node* parent(Node* temp,int num);

public:
bt();
bool isempty();
void insert(int item);
void inorder();
Node* search(int num);
int min();
int max();
Node* parent(int num);
};
bt::bt()
{
root=NULL;
}
void bt::insert(int item)
{
insert(item,root);

}
void bt::insert(int item, Node *tree)
{
Node* ptr=new Node;
ptr->data=item;
ptr->left=NULL;
ptr->right=NULL;
if(root==NULL)
{
root=ptr;
}
else
{
if(item<=tree->data)//left or equal
{
if(tree->left==NULL)
tree->left=ptr;

else
insert(item,tree->left);

if(item>tree->data)//right
{
if(tree->right==NULL)
tree->right=ptr;

else
insert(item,tree->right);
}
}

}
void bt::inorder()
{
inorder(root);
}
void bt::inorder(Node* tree)
{
if(tree!=NULL)
{
inorder(tree->left);
cout<<tree->data<<endl;
inorder(tree->right);
}

}
Node* bt::search(int num)
{
return search(root,num);
}
Node* bt::search(Node* tree,int num)
{
if(tree!=NULL)
{
if(tree->data==num)
return tree;
else if(tree->data<num)
search(tree->right,num);
else if(tree->data>num)
search(tree->left,num);
}
else if(tree==NULL)
{
cout<<"tree is empty or value not found"<<endl;
return NULL;
}
}

int bt::min()
{
return min(root);
}
int bt::min(Node* temp)
{
Node* ptr;
ptr=root;
while(ptr->left!=NULL)
{
ptr=ptr->left;
}
return ptr->data;
}
int bt::max()
{
return max(root);
}
int bt::max(Node* temp)
{
Node* ptr;
ptr=root;
while(ptr->right!=NULL)
{
ptr=ptr->right;
}
return ptr->data;
}
Node* bt::parent(int num)
{
return parent(root,num);
}
Node* bt::parent(Node* temp,int num)
{
if(temp!=NULL)
{
if(num==temp->right->data||num==temp->left->data)
{
return temp;}
else if(temp->data<num)
parent(temp->right,num);
else if(temp->data>num)
parent(temp->left,num);
}
else if(temp==NULL)
{
cout<<"tree is empty or value not found"<<endl;
return NULL;
}
}
void bt::genratetree()
{
string str;
stack<Node*> s;
cout<<"Enter expression";
getline(cin,str);
for(unsigned i=0;i<str.length();i++)
{
Node* curr=new Node;
if(str[i]=='+'||str[i]=='*'||)
{
Node* T2=new Node;
T2=s.top();
s.pop();
Node* T1=new Node;
T1=s.top();
s.pop();
curr->data=str[i];
curr->left=T1;
curr->right=T2;
s.push(curr);

}
else
{
curr->data=int(48)-int(str[i]);
curr->left=NULL;
curr->right=NULL;
s.push(curr);

}
root=curr;

void main()
{
bt b;
b.insert(13);
b.insert(7);
b.insert(21);
b.insert(9);
cout<<"min:"<<b.min()<<endl;
cout<<"max:"<<b.max()<<endl;
cout<<"Address:"<<b.parent(9)<<endl;
system("pause");

You might also like