10

Tried exploring a lot over the net, but could get any help, Everywhere its like adding a node to the Binary Search tree.

Question: Requesting for algorithm and code snippet for adding a node to the Binary tree. ( or point me to correct URL )

Assumption: As per my understanding, Binary Tree and Binary Search Tree is different? Correct me if I am wrong.

( request: if you are writing your code snippet please use proper variable name, that helps in understanding )

Eg: Binary Tree

5 7 3 x1 x2 x3

                 5

          7               3

   x1       x2       x3       

Binary Search Tree 5 7 3 2 4 6

                   5
          3               7

   2          4       6       





insert(int key, struct node **root)
{
    if( NULL == *root )`
    {
        *root = (struct node*) malloc( sizeof( struct node ) );`
        (*root)->data = key;
        (*root)->left = NULL;    
        (*root)->right = NULL;  
    }
    else if(key < (*root)->data)
    {
        insert( key, &(*root)->left );
    }
    else if(key > (*root)->data)
    {
        insert( key, &(*root)->right );
    }
}
sbru
  • 877
  • 6
  • 21
  • 36
Raa
  • 321
  • 2
  • 5
  • 16
  • If you are talking about binary search tree and if you are trying to do some instertion, maybe this could help?: http://en.wikipedia.org/wiki/Binary_search_tree#Insertion – CLearner Apr 30 '13 at 05:33
  • Wrong binary search tree – Abdullah Shoaib Apr 30 '13 at 05:33
  • @AbdullahShoaib Tell me what will be the right order of BST. – Raa Apr 30 '13 at 16:33
  • @Cleaner : insertHelper() at the given link also checks for the value < node->key , where as Binary tree should not bother whether the value is less or greater. it should go ahead and place the next node to left if its available or else to right. I hope you understand whats the difference between Binary tree and Binary Search Tree is? according to that do you think its correct. – Raa Apr 30 '13 at 16:37
  • BTW: the example in the question looks like a binary *search* tree to me. – wildplasser Apr 30 '13 at 18:00
  • 1
    @wildplasser : yes its a BST , I am looking for the Binary tree.. not getting an algorithm to do the same – Raa Apr 30 '13 at 20:18
  • A binary Search tree is a Binary Tree with an *imposed order*. A binary tree is just a tree where every node has two child nodes (or fewer), *without* any restrictions on the order. – wildplasser Apr 30 '13 at 20:22
  • @wildplasser : Thanks, but I am not getting how exactly to modify my code to insert the node in a Binary tree – Raa Apr 30 '13 at 20:26
  • It is the same. Just replace your compare `(key > (*root)->key)` by a random decision. Anything goes... – wildplasser Apr 30 '13 at 20:30

5 Answers5

9

The difference between a Binary Tree and a Binary Search Tree is that though they both have restrictions that each node can have at most 2 child nodes, a Binary Search Tree (BST) also must have its left child be of equal or lesser value and the its right child must be of greater or equal value. This is why it is called a "Search" tree because everything is ordered numerically and it has an O(logn) run time for searching.

Because there isn't the requirement of being a BST, a Binary Tree can be stored in a vector (array). As you insert into the vector you build the Binary Tree in level-order fashion. The code is below:

// typedef the node struct to NODE
// nodeVector similar to STL's vector class
insert(int key, NODE** nodeVector)
{
    NODE *newNode = (NODE*) malloc( sizeof( NODE ) );
    newNode->data = key;
    newNode->left = NULL;    
    newNode->right = NULL;

    // add newNode to end of vector
    int size = nodeVector->size();
    nodeVector->push_back(newNode);

    // if newNode is not root node
    if(nodeVector->size() > 1)
    {
        // set parent's child values
        Node* parent = (size/2)-1; // take advantage of integer division instead of using floor()
        if (parent->left == NULL)
        {
            parent->left = newNode;
        }
        else
        {
            parent->right = newNode;
        }
    }
}
sbru
  • 877
  • 6
  • 21
  • 36
  • Thanks for the clarification @bagel. I have updated my BST code for insertion, can you please suggest what changes should i incorporate to make this BST to Binary tree – Raa Apr 30 '13 at 16:43
  • post the code you are currently using and I'll see what I can do. – sbru Apr 30 '13 at 16:59
  • just posed it in the question, as i was a bit struggling to get it formatted. please ignore ` character. – Raa Apr 30 '13 at 17:01
  • what should my left value when I am calling the insert() function from my main ? – Raa Apr 30 '13 at 20:28
  • it can be either true or false, it doesn't really matter, that bool is just to make it so it is not a linked list. – sbru Apr 30 '13 at 23:31
  • @bagelboy: If we follow your code for insertion of 10,7,8,12,9. This is my output.
    10 / \ 7 8 / \ 12 9 and my tree will keep growing on the right side leaving the left side unoccupied.
    – Ravi Mar 06 '16 at 20:00
  • @bagelboy: If we follow your code for insertion of 10,7,8,12,9. This is my output. node 10 (root) - left child 7, right child 8 & for node 7 - No children & for node 8 - left child 12, right child 9 and my tree will keep growing on the right side leaving the left side unoccupied. – Ravi Mar 06 '16 at 20:06
  • 1
    @Ravi you are correct. To be fair, a Binary Tree (or BST for that matter) has no requirements on being balanced so technically this isn't incorrect. If that is an additional requirement you want in your BST then take a look at AVL trees. That being said, you are totally in the right having issues with my code because this is almost identical to a linked list. So now, with another 2 years of education under my belt I will attempt to provide a more desirable solution. :) – sbru Sep 27 '16 at 19:26
2

A Queue data structure can be used for inserting element in to a Binary Tree, since in Binary Tree the order of nodes is not maintained so we will insert the node as soon as we find any null. Using Queue we will be traversing the Binary Tree in Level Order Traversal.

struct Treenode* temp;

Q = CreateQueue();
EnQueue(Q,root);

while(!IsEmptyQueue(Q))
{
    temp = DeQueue(Q);
    if(temp->left)
        EnQueue(Q,temp->left);
    else
    {
        temp->left=newNode;
        DeleteQueue(Q);
        return;
     }
     if(temp->right)
        EnQueue(Q,temp->right);
    else
    {
        temp->right=newNode;
        DeleteQueue(Q);
        return;
     }
}
user905
  • 250
  • 4
  • 14
0

Since, I cannot comment I am writing this.
The above answer for binary tree insert function is wrong.
Suppose for 0, 1, 2 , 3, 4 , 5 passed in sequence to insert function,
its generating tree like

       0
      /
     1
      \ 
       2
      /
     3
      \
       4
      /
     5`<br/>

of which inorder traversal will be 1 3 5 4 2 0
while answer should be

                     0
                   /  \
                  1    2 
                 / \  /  
                3   4 5


of which inorder traversal will be 3 1 4 0 5 2.

codeFreak
  • 164
  • 9
  • 1
    You are correct, upon coming back to this answer 1.5 years further through my degree I see my mistake :). I'll attempt to fix the issue. Thanks – sbru Dec 22 '14 at 00:39
  • 1
    Ok, I've made some changes, what are your thoughts on it now? – sbru Dec 22 '14 at 00:48
  • @bagelboy: I still have issues with your code. I am commenting under your post directly. – Ravi Mar 06 '16 at 19:59
0

Since I also face the same problem, I came up with following solution over the net :-

You can use a queue to store the current node where we want to place the new node as we do in level order traversal and then we insert the nodes level by level.

Following link might help you :-

http://www.geeksforgeeks.org/linked-complete-binary-tree-its-creation/

anonymous
  • 9
  • 1
0

I am posting this as answer because I dont have the necessary reputation to post a comment. Except for bagelboy all others have misunderstood the tree as either Binary Search Tree or Complete Binary Tree. The question is simple Binary Tree and Bagelboy's answer looks correct.

takesavy
  • 135
  • 2
  • 16