Basic Binary Tree data Structure.
Posted: Mon Nov 03, 2008 7:59 pm
here is a C++ implementation of a binary tree. binary trees are very powerful tools.
i didn't comment anything, sorry. if you have any questions please feel free to ask. the recursive function might be hard to understand at first.
it traverses the tree in "inorder" other options are pre, and postorder, but will not yeild the correct output. but is still interesting to look at.
Code: Select all
#include <iostream>
using namespace std;
typedef struct node
{
int val;
node *rNode;
node *lNode;
} node;
class bTree
{
public:
bTree();
node *add_Node(node *tRoot, int data);
void print_Tree(node *tree);
node *root;
};
bTree::bTree()
{
this->root = new node;
this->root = NULL;
cout << "Tree Created." << endl;
}
node *bTree::add_Node(node *tRoot, int data)
{
if(tRoot == NULL)
{
tRoot=new node;
tRoot->lNode = NULL;
tRoot->rNode = NULL;
tRoot->val = data;
}else
if(data < tRoot->val)
tRoot->lNode = this->add_Node(tRoot->lNode, data);
else
tRoot->rNode = this->add_Node(tRoot->rNode, data);
return tRoot;
}
void bTree::print_Tree(node* tree)
{
if(tree != NULL)
{
this->print_Tree(tree->lNode);
cout<< tree->val << endl;
this->print_Tree(tree->rNode);
}
}
int main(void)
{
cout << "Start of program" << endl;
bTree* tree = new bTree();
tree->root = tree->add_Node(tree->root, 100);
tree->root = tree->add_Node(tree->root, 12);
tree->root = tree->add_Node(tree->root, 1040);
tree->root = tree->add_Node(tree->root, 1023);
tree->root = tree->add_Node(tree->root, 1450);
tree->root = tree->add_Node(tree->root, 1);
tree->root = tree->add_Node(tree->root, 156);
tree->root = tree->add_Node(tree->root, 10222);
tree->root = tree->add_Node(tree->root, 130);
tree->root = tree->add_Node(tree->root, 156);
tree->root = tree->add_Node(tree->root, 2);
tree->root = tree->add_Node(tree->root, 101);
tree->print_Tree(tree->root);
cin.get();
}
it traverses the tree in "inorder" other options are pre, and postorder, but will not yeild the correct output. but is still interesting to look at.