/// <summary> /// Adds a new child to this node. /// </summary> /// <param name="c">Next character in the prefix</param> /// <returns>The new node</returns> public PrefixTreeNode AddChild(char c) { var newNode = new PrefixTreeNode(c); Children[c] = newNode; return(newNode); }
/// <summary> /// Given a start node, recursively collects all the full terms and their posting list ids contained in the subtree. /// </summary> /// <param name="currentNode"></param> /// <param name="currentPrefix">Used to reconstruct the full term, so that we know which posting list id is for which term.</param> /// <param name="result">Reference to the list that will contain the result.</param> private void CollectSubtreeEntriesRecursive(PrefixTreeNode currentNode, string currentPrefix, ref List <PrefixResult> result) { if (currentNode.PostingListId.HasValue) { result.Add(new PrefixResult { Term = currentPrefix, PostingListId = currentNode.PostingListId.Value }); } foreach (var node in currentNode.Children.Values) { CollectSubtreeEntriesRecursive(node, currentPrefix + node.Prefix, ref result); } }
/// <summary> /// Recursively finds the node that has the exact prefix that's given. /// </summary> /// <param name="currentNode"></param> /// <param name="prefix"></param> /// <returns>Node with the exact prefix or null if such a node doesn't exist.</returns> private PrefixTreeNode FindNodeRecursive(PrefixTreeNode currentNode, string prefix) { if (string.IsNullOrEmpty(prefix)) { return(currentNode); } char nextChar = prefix[0]; if (currentNode.Children.ContainsKey(nextChar)) { return(FindNodeRecursive(currentNode.Children[nextChar], prefix.Substring(1))); } else { return(null); } }
/// <summary> /// Recursive function for adding new terms to the tree. /// Steps through the tree character by character, creating new nodes if needed. /// When the appropriate leaf node is reached, sets its value to postingListId. /// </summary> /// <param name="currentNode"></param> /// <param name="prefix"></param> /// <param name="postingListId"></param> private void AddRecursive(PrefixTreeNode currentNode, string prefix, int postingListId) { if (string.IsNullOrEmpty(prefix)) // We have reached the leaf node { currentNode.PostingListId = postingListId; return; } char nextChar = prefix[0]; if (currentNode.Children.ContainsKey(nextChar)) { AddRecursive(currentNode.Children[nextChar], prefix.Substring(1), postingListId); } else { AddRecursive(currentNode.AddChild(nextChar), prefix.Substring(1), postingListId); } }