Find K nodes in BST that are closest to a value key (Part I).

Question:

There is a BST while each node has distinct values, then for a given value key, find out K nodes in this BST such that their values are closest to key.

Solution:

It seems to be a very easy question, all we need to do is to do a pre-order traversal and store all the nodes in this BST to an array, and then find out the K numbers that are the nearest to key. However, This approach takes O(n) time.

It is introduced in this blog an O(log(n)) approach with the assumption that the node in BST has “Parent” pointer.

The algorithm can go as following:

1) Start from the root node to find out the node (denoted as the closestNode) whose value is the closest to key.
2) Generate two functions the nextLargerNodeInBST() and nextSmallerNodeInBST(), using which to find the next larger node of the closestNode, denoted as nextLarger, and find its next smaller node, denoted as nextSmaller.
3) Compare nextSmaller to nextLarger by their difference to key, and update them appropriately until K nodes are selected.

Step 1) costs O(log(n)).
Step 3) It takes at most O(log(n)) to find out next point, and each node in BST is checked at most twice in the entire searching, therefore, the overall time complexity is max {O(K), O(log(n))} = O(log(n))

To sum up, it’s an O(log(n)) approach.

// Main Test Function, step 3)
public static List<Tree> findKClosestNodeInBST(Tree root, int key, int k)
{
    List<Tree> list = new List<Tree>();
    Tree closestNode = findTreeWithKeyNearestToTheKey(root, key);
    k--;
    list.Add(closestNode);
    Tree nextlarger = nextLargerNodeInBST(closestNode);
    Tree nextSmaller = nextSmallerNodeInBST(closestNode);
    while (k > 0)
    {
        if (nextlarger == null && nextSmaller == null)
            throw new StackOverflowException();
        else if (nextlarger != null && nextSmaller != null)
        {
            if (Math.Abs(nextlarger.node - key) >= Math.Abs(nextSmaller.node - key))
            {
                list.Add(nextSmaller);
                k--;
                nextSmaller = nextSmallerNodeInBST(nextSmaller);
            }
            else
            {
                list.Add(nextlarger);
                k--;
                nextlarger = nextLargerNodeInBST(nextlarger);
            }
        }
        else if (nextlarger != null)
        {
            list.Add(nextlarger);
            k--;
            nextlarger = nextLargerNodeInBST(nextlarger);
        }
        else
        {
            list.Add(nextSmaller);
            k--;
            nextSmaller = nextSmallerNodeInBST(nextSmaller);
        }
    }
    return list;
}

//find out the node that is closed to the key, step 1)
public static Tree findTreeWithKeyNearestToTheKey(Tree root, int key)
{
    Tree desiredRoot = root;
    int diff = Math.Abs(root.node - key);
    while (root != null)
    {
        if (diff > Math.Abs(root.node - key))
        {
            diff = Math.Abs(root.node - key);
            desiredRoot = root;
        }
        if (root.node > key)
            root = root.leftChild;
        else if (root.node < key)
            root = root.rightChild;
        else
            return root;
        }
    return desiredRoot;
}

//step 2) find its next larger node in BST
public static Tree nextLargerNodeInBST(Tree current)
{
    if (current.rightChild != null)
    {
        Tree nextTree = current.rightChild;
        while (nextTree.leftChild != null)
            nextTree = nextTree.leftChild;
        return nextTree;
    }
    else
   {
        while (current.parentTree!=null)
        {
            if (current != current.parentTree.rightChild)
                return current.parentTree;
            else
            {
                while(current.parentTree!=null&&current==current.parentTree.rightChild)
                    current = current.parentTree;
                return current.parentTree;
            }
        }
        return null;
    }
}

//step 2) find its next smaller node in BST
public static Tree nextSmallerNodeInBST(Tree current)
{
    if (current.leftChild != null)
    {
        Tree nextTree = current.leftChild;
        while (nextTree.rightChild != null)
            nextTree = nextTree.rightChild;
        return nextTree;
    }
    else
    {
        while (current.parentTree != null)
        {
            if (current == current.parentTree.rightChild)
                return current.parentTree;
            else
           {
                while (current.parentTree != null && current == current.parentTree.leftChild)
                    current = current.parentTree;
                return current.parentTree;
            }
        }
        return null;
    }
}

About Algorithms --- A Lot Of Fun

My merit is I have but only one fault, my fault is I have but only one merit...
This entry was posted in Uncategorized. Bookmark the permalink.

1 Response to Find K nodes in BST that are closest to a value key (Part I).

  1. Pingback: Find K nodes in BST that are closest to a value key (Part II). | Algorithms…..A lot of fun…..

Leave a comment