Users Online

· Guests Online: 53

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C++ Program to Create a Balanced Binary Tree of the Incoming Data

C++ Program to Create a Balanced Binary Tree of the Incoming Data

This is a C++ Program to create a balanced binary tree. In computer science, a self-balancing (or height-balanced) binary search tree is any node-based binary search tree that automatically keeps its height (maximal number of levels below the root) small in the face of arbitrary item insertions and deletions.
Here is source code of the C++ Program to Create a Balanced Binary Tree of the Incoming Data. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

#include <iostream>

using namespace std;

typedef struct bin_tree_node
{
int v;
struct bin_tree_node *left;
struct bin_tree_node *right;
} BTNode;

BTNode *create_bin_tree_node(int v)
{
BTNode *p = new BTNode;

if (p != NULL)
{
p->v = v;
p->left = NULL;
p->right = NULL;
}

return p;
}

void create_balanced_bin_tree(BTNode **root, int arr[], int start, int end)
{
if (start <= end)
{
int mid = (start + end + 1) / 2;

*root = create_bin_tree_node(arr[mid]);
create_balanced_bin_tree(&((*root)->left), arr, start, mid - 1);
create_balanced_bin_tree(&((*root)->right), arr, mid + 1, end);
}
}

void print_bin_tree(BTNode *root)
{
if (root != NULL)
{
cout << root->v << " ";
print_bin_tree(root->left);
print_bin_tree(root->right);
}
}
void print_bin_tree1(BTNode *root)
{
if (root != NULL)
{
print_bin_tree1(root->left);
cout << root->v << " ";
print_bin_tree1(root->right);
}
}

int main(int argc, char* argv[])
{
int arr[30];
for (int i = 0; i < 30; i++)
{
arr[i] = i;
}
BTNode *root = NULL;
create_balanced_bin_tree(&root, arr, 0, 29);
cout << "Preorder of balanced tree is: ";
print_bin_tree(root);
cout << "\nInorder of balanced tree is: ";
print_bin_tree1(root);
return 0;
}

Output:

$ g++ BalancedBinaryTree.cpp
$ a.out

Preorder of balanced tree is: 15 7 3 1 0 2 5 4 6 11 9 8 10 13 12 14 23 19 17 16 18 21 20 22 27 25 24 26 29 28
Inorder of balanced tree is: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

------------------
(program exited with code: 0)
Press return to continue

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.81 seconds
10,818,417 unique visits