CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2015
    Posts
    2

    Finding nearest node (or equal node) in BST using Generics

    Hello all, I am having a hard time getting started on this homework assignment. I'm relatively new to C# as I transferred from a C++ school to a C# school, so far I haven't really enjoyed C#. Generics are still very confusing to me. I understand the concepts of BSTs just fine and how I would do most of the code in C++, but tossing the generics in just frustrates me. Here is a screen shot of the problem, any guidance or advice on how to get this thing started would be great. The basic code has been provided for the BST, he just wants us to primarily write the code that will return the closest match from an argument passed to whichever node in the tree fits, or if it is a match return the node that is a match.
    Last edited by nighthawk1; February 22nd, 2015 at 11:31 PM.

  2. #2
    Join Date
    Feb 2015
    Posts
    2

    Re: Finding nearest node (or equal node) in BST using Generics

    private T FindClosest(T value, OurTreeNode<T> pTmp)
    {
    if (pTmp == null)
    throw new Exception("Null value passed.");

    else if (value.CompareTo(pTmp.Data) < 0)
    {
    if (pTmp.Left != null)
    return FindClosest(value, pTmp.Left);
    else
    return pTmp.Data;
    }
    else if (value.CompareTo(pTmp.Data) > 0)
    {
    if (pTmp.Right != null)
    return FindClosest(value, pTmp.Right);
    else return pTmp.Data;
    }
    else
    return pTmp.Data;

    }



    So I have this to find the closest node, but I am stuck doing one that will find the closest value inside the BST. I know I need to traverse the node and compare all nodes to the value and return whichever turned out to have the smallest difference, but am stuck trying to come up with a way to do this.
    Last edited by nighthawk1; February 22nd, 2015 at 11:31 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured