Binary Tree Insert Algorithm -


i finished implementing binary search tree project working on. went , learned lot. however, need implement regular binary tree... reason has me stumped.

i'm looking way insertnode function..

normally in bst check if data < root insert left , vice versa. however, in normal binary tree, filled left right, 1 level @ time..

could me implement function adds new node binary tree left right in no specific order?

here's insert 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);     }   } } 

thanks appreciated!

i aware of fact question posted time ago, still wanted share thoughts on it.

what (since indeed not documented) use breadth-first-search (using queue) , insert child first null encounter. ensure tree fill levels first before goes level. right number of nodes, complete.

i haven't worked c++, sure correct did in java, idea:

public void insert(node node) {     if(root == null) {         root = node;         return;     }      /* insert using breadth-first-search (queue 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);         }     } } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -