Reputation:
I am trying to create an Unordered Binary tree. How do we insert a Treenode in an unordered Binary tree? What should be the logic?
By inserting here I mean inserting the node as a leaf. Like if I start from the root node and then traverse to the right node, now where do I insert the node.
If anyone has a reference to UNORDERED binary tree[Not BST] implementation please provide.
Upvotes: 1
Views: 777
Reputation:
void addnode(T data){
Node<T>* new_node=new Node<T>(data);
if(this->root==nullptr){
this->root= new_node;
return ;
}else{
std::queue<Node<T>* > Q;
Q.push(this->root);
while(!Q.empty()){
Node<T>* popping_element= Q.front();
Q.pop();
if(!popping_element->left){
popping_element->left=new_node;
return;
}else if(!popping_element->right){
popping_element->right=new_node;
return;
}else{
Q.push(popping_element->left);
Q.push(popping_element->right);
}
}
}
}
What I was trying to do
Add a node as a left child of 30.
This is called Level order insertion in a binary tree. It has no order or it is unsorted both imply the same meaning.
Upvotes: 0