Insert into a Binary Tree

[wpdm_package id=’1373′]
Algorithm:

  • Use the level order traversal or Breadth First Traversal.
  • Insert the element where we find the left/right node as NULL.

[sourcecode lang=”cpp”]
void InsertInBinaryTree(int d)
{ std::queue<tree_node*> Q;
tree_node *temp, *newnode;
newnode=new tree_node(d);
if(!newnode)
{ cout<<"Memory Error";
return;
}
if(!root)
{ root=newnode;
return;
}
Q.push(root);
while(!Q.empty())
{ temp=Q.front();
Q.pop();
if(temp->left)
Q.push(temp->left);
else
{ temp->left=newnode;
return;
}
if(temp->right)
Q.push(temp->right);
else
{ temp->right=newnode;
return;
}
}
}

[/sourcecode]

Leave a Reply

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