|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Text; |
| 4 | + |
| 5 | +namespace DataStructures.Trees |
| 6 | +{ |
| 7 | + public class TernarySearchTree |
| 8 | + { |
| 9 | + public TernaryTreeNode Root { get; private set; } |
| 10 | + |
| 11 | + public void Insert(string word) |
| 12 | + { |
| 13 | + if (string.IsNullOrWhiteSpace(word)) |
| 14 | + throw new Exception("Inputted value is empty"); |
| 15 | + |
| 16 | + if (Root == null) |
| 17 | + Root = new TernaryTreeNode(null, word[0], word.Length == 1); |
| 18 | + |
| 19 | + WordInsertion(word); |
| 20 | + } |
| 21 | + |
| 22 | + public void Insert(string[] words) |
| 23 | + { |
| 24 | + foreach (var word in words) |
| 25 | + { |
| 26 | + Insert(word); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + void WordInsertion(string word) |
| 31 | + { |
| 32 | + int index = 0; |
| 33 | + TernaryTreeNode currentNode = Root; |
| 34 | + |
| 35 | + while (index < word.Length) |
| 36 | + currentNode = ChooseNode(currentNode, word, ref index); |
| 37 | + } |
| 38 | + |
| 39 | + TernaryTreeNode ChooseNode(TernaryTreeNode currentNode, string word, ref int index) |
| 40 | + { |
| 41 | + //Center Branch |
| 42 | + if (word[index] == currentNode.Value) |
| 43 | + { |
| 44 | + index++; |
| 45 | + |
| 46 | + if (currentNode.GetMiddleChild == null) |
| 47 | + InsertInTree(currentNode.AddMiddleChild(word[index], word.Length == index + 1), word, ref index); |
| 48 | + |
| 49 | + |
| 50 | + return currentNode.GetMiddleChild; |
| 51 | + } |
| 52 | + //Right Branch |
| 53 | + else if (word[index] > currentNode.Value) |
| 54 | + { |
| 55 | + if (currentNode.GetRightChild == null) |
| 56 | + InsertInTree(currentNode.AddRightChild(word[index], word.Length == index + 1), word, ref index); |
| 57 | + |
| 58 | + return currentNode.GetRightChild; |
| 59 | + } |
| 60 | + //Left Branch |
| 61 | + else |
| 62 | + { |
| 63 | + if (currentNode.GetLeftChild == null) |
| 64 | + InsertInTree(currentNode.AddLeftChild(word[index], word.Length == index + 1), word, ref index); |
| 65 | + |
| 66 | + return currentNode.GetLeftChild; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + void InsertInTree(TernaryTreeNode currentNode, string word, ref int currentIndex) |
| 71 | + { |
| 72 | + int length = word.Length; |
| 73 | + |
| 74 | + currentIndex++; |
| 75 | + var currNode = currentNode; |
| 76 | + for (int i = currentIndex; i < length; i++) |
| 77 | + currNode = currNode.AddMiddleChild(word[i], word.Length == currentIndex + 1); |
| 78 | + |
| 79 | + currentIndex = length; |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments