blob: 602492e575b3631f3c9e2a0b8c8d7dd20db8e02c (
plain)
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
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace GenericTree
{
/// <summary>
/// Generic tree interface
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
interface ITreeNode<T, U>
where T : ITreeNode<T, U>
{
bool IsValid { get; }
int ValueIndex { get; }
U Value { get; }
bool HasParent { get; }
T Parent { get; }
IEnumerable<T> Children { get; }
}
/// <summary>
/// Item has parent reference by list index
/// </summary>
public interface ITreeItem
{
int ParentIndex { get; }
}
/// <summary>
/// Generic tree implementation
/// </summary>
/// <typeparam name="T"></typeparam>
struct TreeNode<T> : ITreeNode<TreeNode<T>, T>
where T : ITreeItem
{
/// <summary>
/// Whole tree nodes
/// </summary>
public readonly List<T> Values;
public bool IsValid
{
get
{
return Values != null;
}
}
/// <summary>
/// This node index
/// </summary>
public int ValueIndex
{
get;
private set;
}
public T Value
{
get
{
if (Values == null)
{
return default(T);
}
return Values[ValueIndex];
}
}
public IEnumerable<TreeNode<T>> Children
{
get
{
for (int i = 0; i < Values.Count; ++i)
{
if (Values[i].ParentIndex == ValueIndex)
{
yield return new TreeNode<T>(Values, i);
}
}
}
}
public bool HasParent
{
get
{
return Value.ParentIndex >= 0 && Value.ParentIndex < Values.Count;
}
}
public TreeNode<T> Parent
{
get
{
if (Value.ParentIndex < 0)
{
throw new Exception("this may root node");
}
if (Value.ParentIndex >= Values.Count)
{
throw new IndexOutOfRangeException();
}
return new TreeNode<T>(Values, Value.ParentIndex);
}
}
public TreeNode(List<T> values, int index) : this()
{
Values = values;
ValueIndex = index;
}
}
class TreeTests
{
[Test]
public void TreeTest()
{
}
}
}
|