Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
//Inserts Names into the Trie data structure
public static Node InsertNode(string name, Node root)
{
    //Is name null?
    if (string.IsNullOrEmpty(name))
        throw new ArgumentNullException("Null Key");

    //set the index, start inserting characters
    int index = 1;
    
    //key
    string key;

    //start with the root node
    Node currentNode = root;

    //loop for all charecters in the name
    while (index <= name.Length)
    {
        //get the key character
        key = name[index - 1].ToString(); 

        //does the node with same key already exist?
        Node resultNode = currentNode.Children.GetNodeByKey(key);

        //No, this is a new key
        if (resultNode == null)
        {
            //Add a node
            Node newNode = new Node(key, name.Substring(0, index));
            
            //If reached the last charaecter, this is a valid full name
            if (index == name.Length)
                newNode.IsTerminal = true;
            
            //add the node to currentNode(i.e. Root node for the first time)
            currentNode.Children.Add(newNode);

            //set as the current node
            currentNode = newNode;
        }
        else
        {
            //node already exist, set as tghe current node
            //and move to the next character in the name
            currentNode = resultNode;
        }

        //move to the next character in the name
        index++;
    }

    //all done, return root node
    return root;
}




//Find a node given the key("Jo")
public static bool Find(Node node, string key)
{
    //Is key empty
    if (string.IsNullOrEmpty(key))
        return true;//terminal Node

    //get the first character
    string first = key.Substring(0, 1);

    //get the tail: key - first character
    string tail = key.Substring(1);

    Node curNode = node.Children.GetNodeByKey(first);

    //loop until you locate the key i.e. "Jo"
    if (curNode != null)
    {
        return Find(curNode, tail);
    }
    else
    {
        //not found, return false
        return false;
    }
}
Posted
Updated 28-Oct-14 0:52am
v2
Comments
Legor 28-Oct-14 6:47am    
You mind formulating a question? You should also do your homework by yourself.
CPallini 28-Oct-14 6:52am    
And the question is?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900