Home / C++ / Binary Tree example code C++

Binary Tree example code C++

Just create a file Binary.txt in “D drive”, then compile and execute the following code.

#include<iostream>
#include<fstream>
#include<windows.h>
using namespace std;
class BST{
int info;
BST *left;
BST *right;
public:
BST()
{
info = -1;
left = NULL;
right = NULL;
}
void setLeft(BST *aleft)
{
left = aleft;
}
void setRight(BST *aRight)
{
right = aRight;
}
void newRoot(int root)
{
info = root;
}
int Info()
{
return info;
}
BST *Right()
{
return right;
}
BST *Left()
{
return left;
}
};
class Tree{
BST *root;
public:
Tree();
~Tree();
void insertNode(int info);
void insertNode(int info, BST *leaf);
void leafNode(BST *leaf);
BST *Root(){
return root;
}
};
Tree::Tree(){
root=NULL;
}
Tree::~Tree()
{
delete[]  root;
}
void Tree::insertNode(int info)
{
if(root == NULL){
cout<<"\n\n\t\tRoot : " << info;
BST *n = new BST();
n->newRoot(info);
root = n;
}
else{
cout<<"\n\t\tChild : "<<info;
insertNode(info,root);
}
}
void Tree::insertNode(int info, BST* leaf)
{
if ( info <= leaf->Info() )
{
if ( leaf->Left() != NULL )
insertNode(info, leaf->Left());
else
{
BST* n = new BST();
n->newRoot(info);
leaf->setLeft(n);
}
}
else
{
if ( leaf->Right() != NULL )
insertNode(info, leaf->Right());
else
{
BST* n = new BST();
n->newRoot(info);
leaf->setRight(n);
}
}
}
void Tree::leafNode(BST *leaf){
if(root != NULL){
leafNode(leaf->Left());
leafNode(leaf->Right());
delete leaf;
}
}
int main()
{
Tree *node = new Tree();
double x;
x = 0;
ifstream file("D:/Binary.txt");
if(!file.eof()){
file>>x;
node->insertNode(x);
}
}

If you have any other questions then let me know about them in comments, thanks.

Binary Tree example code C++
4 (80%) 1 vote

About

(royal52) is a software engineer. He is good at authoritative link building, Content Writing, SEO, Web Development, Wordpress, HTML, CSS, JAVASCRIPT, Game Development, Unity3d, Graphic Designing, Logo Designing, Android Development and Ios Development. Last but not least, he is passionate about development and gaming.

Check Also

Polymorphism in C++ with Examples

Polymorphism is the capability to use an operator or method in different ways. Polymorphism gives …

Leave a Reply