Skip to content

Commit c494297

Browse files
committed
Made KdTree Enumerable
1 parent 9f7c1d1 commit c494297

File tree

3 files changed

+83
-4
lines changed

3 files changed

+83
-4
lines changed

KdTreeLib/IKdTree.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
namespace KdTree
88
{
9-
public interface IKdTree<TKey, TValue>
9+
public interface IKdTree<TKey, TValue> : IEnumerable<KdTreeNode<TKey, TValue>>
1010
{
1111
bool Add(TKey[] point, TValue value);
1212

KdTreeLib/KdTree.cs

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections;
23
using System.Collections.Generic;
34
using System.IO;
45
using System.Linq;
@@ -553,5 +554,66 @@ public static KdTree<TKey, TValue> LoadFromFile(string filename)
553554
}
554555

555556
}
556-
}
557+
558+
public IEnumerator<KdTreeNode<TKey, TValue>> GetEnumerator()
559+
{
560+
var left = new Stack<KdTreeNode<TKey, TValue>>();
561+
var right = new Stack<KdTreeNode<TKey, TValue>>();
562+
563+
Action<KdTreeNode<TKey, TValue>> addLeft = node =>
564+
{
565+
if (node.LeftChild != null)
566+
{
567+
left.Push(node.LeftChild);
568+
}
569+
};
570+
571+
Action<KdTreeNode<TKey, TValue>> addRight = node =>
572+
{
573+
if (node.RightChild != null)
574+
{
575+
right.Push(node.RightChild);
576+
}
577+
};
578+
579+
if (root != null)
580+
{
581+
yield return root;
582+
583+
addLeft(root);
584+
addRight(root);
585+
586+
while (true)
587+
{
588+
if (left.Any())
589+
{
590+
var item = left.Pop();
591+
592+
addLeft(item);
593+
addRight(item);
594+
595+
yield return item;
596+
}
597+
else if (right.Any())
598+
{
599+
var item = right.Pop();
600+
601+
addLeft(item);
602+
addRight(item);
603+
604+
yield return item;
605+
}
606+
else
607+
{
608+
break;
609+
}
610+
}
611+
}
612+
}
613+
614+
IEnumerator IEnumerable.GetEnumerator()
615+
{
616+
return GetEnumerator();
617+
}
618+
}
557619
}

KdTreeTestsLib/KdTreeTests.cs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
using System.Collections.Generic;
33
using System.Linq;
44
using Microsoft.VisualStudio.TestTools.UnitTesting;
5-
using KdTree;
65
using KdTree.Math;
76

87
struct City
@@ -266,5 +265,23 @@ public void TestGetNearestNeighbours()
266265
}
267266
}
268267
}
269-
}
268+
269+
[TestMethod]
270+
[TestCategory("KdTree")]
271+
public void TestEnumerable()
272+
{
273+
AddTestNodes();
274+
275+
foreach (var node in tree)
276+
{
277+
var testNode = testNodes.FirstOrDefault(n => n.Point == node.Point && n.Value == node.Value);
278+
279+
Assert.IsNotNull(testNode);
280+
281+
testNodes.Remove(testNode);
282+
}
283+
284+
Assert.AreEqual(0, testNodes.Count);
285+
}
286+
}
270287
}

0 commit comments

Comments
 (0)