DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
DisplayNode.cpp
#include <iostream>
using namespace std;
class node
{
public:
node (int data);
int data;
node *left, *right;
private:
};
class tree
{
public:
tree (int data);
void add (int data);
void display ();
private:
node *first;
};
node::node (int data)
{
left = NULL;
this->data = data;
right = NULL;
};
tree::tree (int data)
{
first = new node(data);
}
void addnode(node *l, int data)
{
if (data < l->data)
if (l->left == NULL)
l->left = new node (data);
else
addnode (l->left, data);
else
if (l->right == NULL)
l->right = new node (data);
else
addnode (l->right, data);
}
void tree::add(int data)
{
addnode (first, data);
}
void displaynode (node *l)
{
if (l == NULL)
return;
else
{
// Display all the elements in the binary tree in a visual fashion
cout << l->data << endl; // Left Element
cout << "\t\t\t " << "/ \\" << endl;
cout << "\t\t\t " << l->left->data << "\t " << l->right->data << endl;
cout << "\t\t\t " << "/" << " " << "/" << endl;
cout << "\t\t\t " << l->left->left->data << "\t " << l->right->left->data << endl;
}
}
void tree::display()
{
cout << "\t\t\t\t";
displaynode(first);
}
main ()
{
tree b(3); // The "First" root node is initialized using the tree function.
b.add (2); // The elements of the binary tree are recursively added to the binary tree
b.add (1); // These elemets are by no means sorted yet - they simply "grow" the tree.
b.add (5); // They, simply, are being appended to the tree by magnitude of order
b.add (4); // The relatively smaller elements are pushed to the left nodes.
cout << endl << endl << endl;
cout << "\tBefore the nodes of the binary tree were pushed into tree" << endl;
cout << "\tcausing it to grow, they were in the order : " << endl;
cout << "\t3 .. 2.. 1.. 5.. 4.." << endl << endl;
cout << "\tPress [ENTER] to visualize the (Binary) Tree" << endl;
getchar(); cout << endl << endl;
b.display(); cout << endl << endl;
cout << "\t\"It is an immutable law in business that words are words, explanations are explanations," << endl;
cout << "\tpromises are promises but only performance is reality.\" - Harold S. Green" << endl << endl;
getchar();
}




