Binary Tree in C++ Program is given below:
// Binary Tree in C++
// A very basic Binary Tree program in C++
#include "stdafx.h" //Comment this line if it creates any error.
#include <iostream>
using namespace std;
//////////////////////////////////////////////////////////////
struct nodeType{
nodeType();
int info;
nodeType* father;
nodeType* left;
nodeType* right;
};
nodeType::nodeType(){
father = left = right = NULL;
}
//////////////////////////////////////////////////////////////
class binaryTree{
public:
binaryTree(){ root = NULL;
}
//------------------------------------------------------------
nodeType* makeTree(int x){
nodeType* p = new nodeType;
p->info = x;
p->father = NULL;
p->right = NULL;
p->left = NULL;
root = p;
return p;
}
//------------------------------------------------------------
void setLeft(nodeType* p, int x){
if (p == NULL){
cout << "Void Insertion!" << endl;
}
else if (p->left != NULL){
cout << "Invalid Insertion" << endl;
}
else{
p->left = new nodeType;
p->left->info = x;
p->left->right = NULL;
p->left->left = NULL;
p->left->father = p;
}
}
//------------------------------------------------------------
void setRight(nodeType* p, int x){
if (p==NULL){
cout << "Void Insertion" <<endl;
}
else if (p->right != NULL){
cout << "Invalid Insertion" << endl;
}
else{
p->right = new nodeType;
p->right->info = x;
p->right->left = NULL;
p->right->right = NULL;
p->right->father = p;
}
}
//------------------------------------------------------------
nodeType* getRoot(){
return root;
}
//------------------------------------------------------------
void print(nodeType* p){
cout << p->info << endl;
if (p!=NULL && p->left == NULL && p->right == NULL)
return ;
if (p!=NULL && p->left != NULL && p->right == NULL)
print (p->left);
if (p!=NULL && p->left == NULL && p->right != NULL)
print (p->right);
if (p!=NULL && p->left != NULL && p->right != NULL){
print (p->left);
print (p->right);
}
}
//----------------------------------------------------------------
//----------------------------------------------------------------
private:
nodeType* root;
};
//////////////////////////////////////////////////////////////
int main(){
binaryTree obj;
// We insert 3 nodes in Binary Tree. You can try inserting more
obj.makeTree(5);
obj.setLeft(obj.getRoot(),4);
obj.setRight(obj.getRoot(),6);
obj.print(obj.getRoot());
return 0;
}
Now see Generic
Binary Tree in C++ Program to insert at the correct position in the binary tree.