-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree.cs
132 lines (116 loc) · 3.6 KB
/
Tree.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
using System;
using System.Collections.Generic;
using System.Text;
namespace lab3
{
class Tree
{
TreeNode Head;
public Tree()
{
Head = new TreeNode('a', 'z');
}
public List<(int, int, int)> GetInfo(string word)
{
return Search(ref Head, ref word, 0);
}
public void InsertWord(string word, int fileIndex, int row, int col)
{
BuildTree(ref Head, ref word, 0, 'a', 'z', ref fileIndex, ref row, ref col);
}
void BuildTree(ref TreeNode node, ref string word, int pos, char leftBound, char rightBound,
ref int fileIndex, ref int row, ref int column)
{
if (node == null)
{
node = new TreeNode(leftBound, rightBound);
}
if (node.IsLeaf)
{
if (word.Length != pos + 1)
{
BuildTree(ref node.GetLeft(), ref word, pos + 1, 'a', 'z',
ref fileIndex, ref row, ref column);
}
else
{
node.GetInfo().Add((fileIndex, row, column));
}
}
else
{
char middle = Convert.ToChar((leftBound + rightBound) / 2);
if (word[pos] <= middle)
{
BuildTree(ref node.GetLeft(), ref word, pos, leftBound, middle,
ref fileIndex, ref row, ref column);
}
else
{
BuildTree(ref node.GetRight(), ref word, pos, Convert.ToChar(middle + 1), rightBound,
ref fileIndex, ref row, ref column);
}
}
}
List<(int, int, int)> Search(ref TreeNode node, ref string word, int pos)
{
if (node == null)
{
return null;
}
if (node.IsLeaf)
{
if (word.Length != pos + 1)
{
return Search(ref node.GetLeft(), ref word, pos + 1);
}
else
{
return node.GetInfo();
}
}
else
{
char middle = Convert.ToChar((node.LeftBound + node.RightBound) / 2);
if (word[pos] <= middle)
{
return Search(ref node.GetLeft(), ref word, pos);
}
else
{
return Search(ref node.GetRight(), ref word, pos);
}
}
}
}
class TreeNode
{
TreeNode _left, _right;
List<(int, int, int)> _info;
public char LeftBound { get; }
public char RightBound { get; }
public bool IsLeaf { get; }
public TreeNode(char leftBound, char rightBound)
{
LeftBound = leftBound;
RightBound = rightBound;
IsLeaf = (leftBound == rightBound);
if (IsLeaf)
{
_info = new List<(int, int, int)>();
}
}
public ref TreeNode GetLeft()
{
return ref _left;
}
public ref TreeNode GetRight()
{
return ref _right;
}
public ref List<(int, int, int)> GetInfo()
{
return ref _info;
}
}
}