Search code examples
javabinary-search-treenodes

Ascending and descending sorting using BST insert method query


I want to insert a new object newPat as a binary node to the BST in descending order of urgency data field. I am doing the below code in ascending order. How can I change it to descending order?

BST class:

public void insertPatient(Patient newPat)
{
    BNode temp = new BNode(newPat);
    root = insert(root, temp);
}


protected BNode insert(BNode rt, BNode newNode)
{
    //attach newnode to correct subtree keeping ascending order and returns pointer to the node which it was called
    if(rt == null){
        rt = newNode; //last node becomes root           
    }else 
    {
        if((newNode.obj.getKey().compareTo(rt.obj.getKey()) < 0))
        {
            rt.left = insert (rt.left, newNode);
        } 
        else 
        {
            rt.right = insert (rt.right, newNode);
        }
    }
    return rt;
}

Solution

    1. In a Binary Search Tree(as per common understanding), root will not be minimum or maximum(unless your insertion order ensure or rotations are performed to manage the property. in such case, it will have worst case time complexity)
    2. If you always need the minimum or maximum, try looking into Binomial Heap

    Update based on author's clarification

    As the existing code is inserting lesser values to left subtree and bigger values to the right subtree, changing the < to >= should solve your use case.

        protected BNode insert(BNode parent, BNode newNode) {
            if (parent == null) {
                return newNode;
            }
            if (newNode.obj.getKey().compareTo(parent.obj.getKey()) >= 0) {
                parent.left = insert (parent.left, newNode);
            } else {
                parent.right = insert (parent.right, newNode);
            }
            return parent;
        }
    

    With this new property of descending, ensure to update your search function also from < to >=. Else insert will work and search will fail to recognize the node.

    Suggestion

    Alternatively, the insertion order can remain the same and retrieval logic can be changed to traverse the (ascending) tree from right to left to get the same behavior.

    Keeping the existing code as it is for insertion (< comparison)

        protected List<Patient> descendingInorder(BNode node, List<Patient> values) {
            if (node == null) {
                return values;
            }
            descendingInorder(node.right, values);
            values.add(node.obj);
            descendingInorder(node.left, values);
            return values;
        }
    

    Note

    1. If the tree can contain, duplicates, then ensure to define the behavior for that.