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