Binary tree Implementation on C++ – Algorithm and Source Code

Algorithm for inserting a node in a binary tree

1. Declare and initialize necessary variables
2. Read the data item to be inserted in the tree say x.
3. Create a new node with its left and right pointers to null.
4. Assign data x to info field of new node.
5. If (tree == NULL)
then tree = address of new node
else if (x < tree -> info)
if(tree->left == NULL)
then tree->left = new node
else
tree = tree->left
repeat step 5.
else if(x>tree->info)
if(tree->right == NULL)
then tree->right = new node
else
tree = tree->right
repeat step 5
else if(x == tree->info)
print “Duplicated data” and exit
6. For next insertion, goto step 5.

Deletion Algorithm

1. Declare and initialize the necessary variable
2. Read data to be deleted say x.
3. Find the enode where data exist.
if node is not found
print “node not found” and exit
4. If the node has no subtree
* then assign the father node’s pointer with null that points to the node
* delete the node that contains data item.
5. If the node has to be deleted has only one subtree
* move its son up, to take its place
* delete the node that contains data item
6. If the node has to be deleted has two subtrees
* set the information of node to be deleted by the information of leftmost node of rightmost subtree of the node to be deleted
7. For next deletion, goto step 2

Source Code for Insertion , Deletion, inorder, preorder and postorder tree traversal

The code is also available on GitHub.

For the updated and more detailed explanation of the Binary Search Tree click here.

SHARE Binary tree Implementation on C++ – Algorithm and Source Code

You may also like...

4 Responses

  1. Napster says:

    the program given here is not working ????
    anybody help me…..

  2. Napster says:

    the program given here is not working?????????
    plz anybody give some guidlines

  3. Unknown says:

    the pgm is length but useful one sir….ur great

Leave a Reply

Your email address will not be published. Required fields are marked *

Share