1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 3
    I never heard of an unordered binary tree. Are you sure you don't mean "unbalanced"? – Rene Jun 16 '20 at 04:41
  • " If we do not care to regard two trees as different when they differ only in the respective ordering of subtrees of nodes, the tree is said to be unordered. " Can you relate? –  Jun 16 '20 at 04:43
  • I've done unsorted trees (backing store for rope as an example) but not unordered. If it's truly unordered a binary tree probably isn't the right structure. – SoronelHaetir Jun 16 '20 at 04:58
  • @Tushar So each tree itself is ordered (quote: "differ only in the respective ordering"), only when comparing two trees the order of the elements in the trees should matter. E.g. two trees where one orders the elements ascending and the other descending would be called "unordered". Finally this means (I think): Implement a sorted binary tree. If you really want to do an unordered binary tree, here you find some solutions for Java that should be easy to adapt: https://stackoverflow.com/questions/30146632/what-is-the-most-efficient-way-to-build-an-unsorted-binary-tree-in-java – Rene Jun 16 '20 at 20:34

1 Answers1

0
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 Tree Structure 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.