Binary Tree Insert Algorithm

48,386

Solution 1

I am aware of the fact that this is a question posted some time ago, but I still wanted to share my thoughts on it.

What I would do (since this indeed is not very well documented) is use a Breadth-First-Search (using a queue) and insert the child into the first null I encounter. This will ensure that your tree will fill up the levels first before it goes to another level. With the right number of nodes, it will always be complete.

I haven't worked that much with c++, so to be sure it was correct I did it in Java, but you get the idea:

public void insert(Node node) {
    if(root == null) {
        root = node;
        return;
    }

    /* insert using Breadth-first-search (queue to the rescue!) */
    Queue<Node> queue = new LinkedList<Node>();
    queue.offer(root);

    while(true) {
        Node n = queue.remove();
        if(!n.visited) System.out.println(n.data);
        n.visited = true;

        if(n.left == null) {
            n.left = node;
            break;
        } else {
            queue.offer(n.left);
        }           

        if(n.right == null) {
            n.right = node;
            break;
        } else {
            queue.offer(n.right);
        }
    }
}

Solution 2

Javascript implementation (copy-paste ready for your web console):

ES6 implementation (newer javscript syntax with class keyword)

  class BinaryTree {
      constructor(value){
          this.root = value;
          this.left = null;
          this.right = null;
      }

      insert(value){
          var queue = [];
          queue.push(this); //push the root
          while(true){
              var node = queue.pop();
              if(node.left === null){
                  node.left = new BinaryTree(value);
                  return;
              } else {
                  queue.unshift(node.left)
              }

              if(node.right === null){
                node.right = new BinaryTree(value);
                return;
              } else {
                queue.unshift(node.right)
              }
          }
      }
  }

  var myBinaryTree = new BinaryTree(5);
  myBinaryTree.insert(4);
  myBinaryTree.insert(3);
  myBinaryTree.insert(2);
  myBinaryTree.insert(1);

     5
   /   \
  4     3
 / \   (next insertions here)
 2  1    

Pseudoclassical pattern implementation

  var BinaryTree = function(value){
    this.root = value;
    this.left = null;
    this.right = null;
  }

  BinaryTree.prototype.insert = function(value){
    //same logic as before
  }

Solution 3

With a few modifications to your code, I hope this should help :

Node * Insert(Node * root, int data)
{
  if(root == nullptr)
  {
    Node * NN = new Node();
    root = NN;
    root->data = data;
    root->left = root ->right = NULL;

  }
  else
  {
    if(data < root->data)
    { 
      root->left = Insert(root->left, data);
    }
    else
    {
      root->right = Insert(root->right, data);
    }
  }
  return root;
}

Hence , this function returns the root node of the updated BST.

Solution 4

I took bknopper code, modified a little bit and translated to C++. As he stated, surprisingly, this is not well documented.

Here is the node structure and the insert function:

struct nodo
{
    nodo(): izd(NULL), der(NULL) {};
    int val;
    struct nodo* izd;
    struct nodo* der;
};

void inserta(struct nodo** raiz, int num)
{

if( !(*raiz) )
{
    *raiz = new struct nodo;
    (*raiz)->val = num;
}
else
{

    std::deque<struct nodo*>  cola;
    cola.push_back(  *raiz  );

    while(true)
    {
        struct nodo *n = cola.front();
        cola.pop_front();

        if( !n->izd ) {
            n->izd = new struct nodo;
            n->izd->val = num;
            break;
        } else {
            cola.push_back(n->izd);
        }

        if( !n->der ) {
            n->der = new struct nodo;
            n->der->val = num;
            break;
        } else {
            cola.push_back(n->der);
        }
    }
  }
}

You call it this way: inserta(&root, val);

Being root a pointer to node struct and val the integer value you want to insert.

Hope it helps someone.

Share:
48,386
Taylor
Author by

Taylor

Updated on January 18, 2020

Comments

  • Taylor
    Taylor over 4 years

    I recently finished implementing a Binary search tree for a project I was working on. It went well and I learned a lot. However, now I need to implement a regular Binary Tree... which for some reason has me stumped.

    I'm looking for a way to do my InsertNode function..

    normally in a BST you just check if data < root then insert left and vice versa. However, In a normal Binary tree, it is just filled from left to right, one level at a time..

    could anyone help me implement a function that just adds a new Node to the Binary tree from left to right in no specific order?

    Here's my Insert for a BST:

    void Insert(Node *& root, int data)
    {
      if(root == nullptr)
      {
        Node * NN = new Node;
        root = NN;
      }
      else
      {
        if(data < root->data)
        { 
          Insert(root->left, data);
        }
        else
        {
          Insert(root->right, data);
        }
      }
    }