// Helper method for {@link #GetAverageDepthOfLeaves()}. // Returns the node count for a given node by regarding the node itself and all of // its successors. private int CountTotalLeafRecursively(HybridTrieNode node, int leavesCounter) { if (node != null) { if (!node.HasChildren()) { leavesCounter++; } leavesCounter = CountTotalLeafRecursively(node.LeftChild, leavesCounter); leavesCounter = CountTotalLeafRecursively(node.RightChild, leavesCounter); leavesCounter = CountTotalLeafRecursively(node.MiddleChild, leavesCounter); } return(leavesCounter); }
// Helper method for {@link #GetAverageDepthOfLeaves()}. private int CountTotalLeafDepthRecursively(HybridTrieNode node, int depthCounter, int totalDepth) { if (node != null) { depthCounter++; if (!node.HasChildren()) { totalDepth += depthCounter; } totalDepth = CountTotalLeafDepthRecursively(node.LeftChild, depthCounter, totalDepth); totalDepth = CountTotalLeafDepthRecursively(node.RightChild, depthCounter, totalDepth); totalDepth = CountTotalLeafDepthRecursively(node.MiddleChild, depthCounter, totalDepth); } return(totalDepth); }
private bool RemoveRecursively(HybridTrieNode parent, HybridTrieNode node, char[] key, int position) { if (node == null) { return(false); } var log = true; if (key[position] < node.Character) { log = RemoveRecursively(node, node.LeftChild, key, position); } else if (key[position] > node.Character) { log = RemoveRecursively(node, node.RightChild, key, position); } else { // If we are on our last character. if (position == key.Length - 1) { if (node.IsFinalNode()) { // The node is an end node, remove the end value. node.MakeFinalNode(0); } else { // If there is no end key as it does not exist within the tree. return(false); } } else if (position < key.Length + 1) { log = RemoveRecursively(node, node.MiddleChild, key, position + 1); } } // Only remove if the node's middle child is null and if the node is not an end key. // If log is false, the value has never been found. Thus the key does not exist within this tree. if (log && node.MiddleChild == null && !node.IsFinalNode()) { // Case 1: No children, safe to delete. if (!node.HasChildren()) { Transplant(parent, node, null); } // Case 2: Right is null, transplant it to left. else if (node.RightChild == null) { Transplant(parent, node, node.LeftChild); } // Case 3: Left is null, transplant it to right. else if (node.LeftChild == null) { Transplant(parent, node, node.RightChild); } // Case 4: Both left and right children exists, find successor and transplant. else { HybridTrieNode successor = FindSuccessor(node.RightChild); HybridTrieNode successorParent = FindSuccessorParent(successor); // If successor node has left child(ren). if (successorParent != node) { Transplant(parent, node, node.RightChild); } else { Transplant(parent, node, successor); } // Make the node's left child as left child for successor node. successor.LeftChild = node.LeftChild; } node = null; } return(log); }