My favorites | Sign in
Logo
                
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/*
Copyright 2007-2009 The NGenerics Team
(http://code.google.com/p/ngenerics/wiki/Team)

This program is licensed under the GNU Lesser General Public License (LGPL). You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at http://www.gnu.org/copyleft/lesser.html.
*/


using System;
using System.Collections;
using System.Collections.Generic;
using NGenerics.Patterns.Visitor;
using NGenerics.Util;
using System.Diagnostics.CodeAnalysis;

namespace NGenerics.DataStructures.Trees
{
/// <summary>
/// An implementation of a Binary Tree data structure.
/// </summary>
/// <typeparam name="T">The type of elements in the <see cref="BinaryTree{T}"/>.</typeparam>
#if (!SILVERLIGHT)
[Serializable]
#endif
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public class BinaryTree<T> : ICollection<T>, ITree<T>
{
#region Globals

private BinaryTree<T> leftSubtree;
private BinaryTree<T> rightSubtree;
private T data;

#endregion

#region Construction

/// <param name="data">The data contained in this node.</param>
public BinaryTree(T data) : this(data, null, null) { }

/// <param name="data">The data.</param>
/// <param name="left">The data of the left subtree.</param>
/// <param name="right">The data of the right subtree.</param>
public BinaryTree(T data, T left, T right) : this(data, new BinaryTree<T>(left), new BinaryTree<T>(right)) { }

/// <param name="data">The data contained in this node.</param>
/// <param name="left">The left subtree.</param>
/// <param name="right">The right subtree.</param>
public BinaryTree(T data, BinaryTree<T> left, BinaryTree<T> right)
: this(data, left, right, true)
{
}



/// <param name="data">The data contained in this node.</param>
/// <param name="left">The left subtree.</param>
/// <param name="right">The right subtree.</param>
/// <param name="validateData"><see langword="true"/> to validate <paramref name="data"/>; otherwise <see langword="false"/>.</param>
internal BinaryTree(T data, BinaryTree<T> left, BinaryTree<T> right, bool validateData)
{
#region Validation

//TODO: probably not the most efficient way of doing this but SplayTree needs to use a BinaryTree with null data.
if (validateData)
{
Guard.ArgumentNotNull(data, "data");
}

#endregion

leftSubtree = left;

if (left != null)
{
left.Parent = this;
}

rightSubtree = right;

if (right != null)
{
right.Parent = this;
}

this.data = data;
}



#endregion

#region ICollection<T> Members

/// <inheritdoc />
public bool IsEmpty
{
get
{
return Count == 0;
}
}

/// <inheritdoc />
public bool IsFull
{
get
{
return (leftSubtree != null) && (rightSubtree != null);
}
}

/// <inheritdoc />
public bool Contains(T item)
{
foreach (var thisItem in this)
{
if (item.Equals(thisItem))
{
return true;
}
}

return false;
}

/// <inheritdoc />
public void CopyTo(T[] array, int arrayIndex)
{
Guard.ArgumentNotNull(array, "array");

foreach (var item in this)
{
#region Validation

if (arrayIndex >= array.Length)
{
throw new ArgumentException(Constants.NotEnoughSpaceInTheTargetArray, "array");
}

#endregion

array[arrayIndex++] = item;
}
}

/// <inheritdoc />
public int Count
{
get
{
var count = 0;

if (leftSubtree != null)
{
count++;
}

if (rightSubtree != null)
{
count++;
}

return count;
}
}

/// <inheritdoc />
public void Add(T item)
{
AddItem(new BinaryTree<T>(item));
}

/// <inheritdoc />
public bool Remove(T item)
{
if (leftSubtree != null)
{
if (leftSubtree.data.Equals(item))
{
RemoveLeft();
return true;
}
}

if (rightSubtree != null)
{
if (rightSubtree.data.Equals(item))
{
RemoveRight();
return true;
}
}

return false;
}

/// <summary>
/// Removes the specified child.
/// </summary>
/// <param name="child">The child.</param>
/// <returns>A value indicating whether the child was found (and removed) from this tree.</returns>
public bool Remove(BinaryTree<T> child)
{
if (leftSubtree != null)
{
if (leftSubtree == child)
{
RemoveLeft();
return true;
}
}

if (rightSubtree != null)
{
if (rightSubtree == child)
{
RemoveRight();
return true;
}
}

return false;
}

/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
var stack = new Stack<BinaryTree<T>>();

stack.Push(this);

while (stack.Count > 0)
{
var tree = stack.Pop();

yield return tree.Data;

if (tree.leftSubtree != null)
{
stack.Push(tree.leftSubtree);
}

if (tree.rightSubtree != null)
{
stack.Push(tree.rightSubtree);
}
}
}

/// <inheritdoc />
public virtual void Clear()
{
if (leftSubtree != null)
{
leftSubtree.Parent = null;
leftSubtree = null;
}

if (rightSubtree != null)
{
rightSubtree.Parent = null;
rightSubtree = null;
}
}

#endregion

#region ITree<T> Members

/// <inheritdoc />
void ITree<T>.Add(ITree<T> child)
{
AddItem((BinaryTree<T>)child);
}

/// <inheritdoc />
ITree<T> ITree<T>.GetChild(int index)
{
return GetChild(index);
}

/// <inheritdoc />
bool ITree<T>.Remove(ITree<T> child)
{
return Remove((BinaryTree<T>)child);
}

/// <inheritdoc />
ITree<T> ITree<T>.FindNode(Predicate<T> condition)
{
return FindNode(condition);
}

/// <inheritdoc />
ITree<T> ITree<T>.Parent
{
get
{
return Parent;
}
}

#endregion

#region Public Members

/// <summary>
/// Gets the parent of the current node..
/// </summary>
/// <value>The parent of the current node.</value>
public BinaryTree<T> Parent { get; private set; }

/// <summary>
/// Finds the node with the specified condition. If a node is not found matching
/// the specified condition, null is returned.
/// </summary>
/// <param name="condition">The condition to test.</param>
/// <returns>The first node that matches the condition supplied. If a node is not found, null is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="condition"/> is a null reference (<c>Nothing</c> in Visual Basic).</exception>
public BinaryTree<T> FindNode(Predicate<T> condition)
{
Guard.ArgumentNotNull(condition, "condition");

if (condition(Data))
{
return this;
}

if (leftSubtree != null)
{
var ret = leftSubtree.FindNode(condition);

if (ret != null)
{
return ret;
}
}

if (rightSubtree != null)
{
var ret = rightSubtree.FindNode(condition);

if (ret != null)
{
return ret;
}
}

return null;
}

/// <summary>
/// Gets or sets the left subtree.
/// </summary>
/// <value>The left subtree.</value>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual BinaryTree<T> Left
{
get
{
return leftSubtree;
}
set
{
if (leftSubtree != null)
{
RemoveLeft();
}

if (value != null)
{
if (value.Parent != null)
{
value.Parent.Remove(value);
}

value.Parent = this;
}

leftSubtree = value;
}
}

/// <summary>
/// Gets or sets the right subtree.
/// </summary>
/// <value>The right subtree.</value>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual BinaryTree<T> Right
{
get
{
return rightSubtree;
}
set
{

if (rightSubtree != null)
{
RemoveRight();
}

if (value != null)
{
if (value.Parent != null)
{
value.Parent.Remove(value);
}

value.Parent = this;
}

rightSubtree = value;
}
}

/// <inheritdoc />
public virtual T Data
{
get
{
return data;
}
set
{
#region Validation

Guard.ArgumentNotNull(value, "data");

#endregion

data = value;
}
}

/// <inheritdoc />
public int Degree
{
get
{
return Count;
}
}

/// <summary>
/// Gets the child at the specified index.
/// </summary>
/// <param name="index">The index of the child in question.</param>
/// <returns>The child at the specified index.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> does not equal 0 or 1.</exception>
public BinaryTree<T> GetChild(int index)
{
switch (index)
{
case 0:
return leftSubtree;
case 1:
return rightSubtree;
default:
throw new ArgumentOutOfRangeException("index");
}
}
/// <inheritdoc />
public virtual int Height
{
get
{
if (Degree == 0)
{
return 0;
}

return 1 + FindMaximumChildHeight();
}
}


/// <summary>
/// Performs a depth first traversal on this tree with the specified visitor.
/// </summary>
/// <param name="orderedVisitor">The ordered visitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="orderedVisitor"/> is a null reference (<c>Nothing</c> in Visual Basic).</exception>
public virtual void DepthFirstTraversal(OrderedVisitor<T> orderedVisitor)
{
Guard.ArgumentNotNull(orderedVisitor, "orderedVisitor");

if (orderedVisitor.HasCompleted)
{
return;
}

// Preorder visit
orderedVisitor.VisitPreOrder(Data);

if (leftSubtree != null)
{
leftSubtree.DepthFirstTraversal(orderedVisitor);
}

// In-order visit
orderedVisitor.VisitInOrder(data);

if (rightSubtree != null)
{
rightSubtree.DepthFirstTraversal(orderedVisitor);
}

// PostOrder visit
orderedVisitor.VisitPostOrder(Data);
}

/// <summary>
/// Performs a breadth first traversal on this tree with the specified visitor.
/// </summary>
/// <param name="visitor">The visitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is a null reference (<c>Nothing</c> in Visual Basic).</exception>
public virtual void BreadthFirstTraversal(IVisitor<T> visitor)
{
Guard.ArgumentNotNull(visitor, "visitor");

var queue = new Queue<BinaryTree<T>>();

queue.Enqueue(this);

while (queue.Count > 0)
{
if (visitor.HasCompleted)
{
break;
}

var binaryTree = queue.Dequeue();
visitor.Visit(binaryTree.Data);

for (var i = 0; i < binaryTree.Degree; i++)
{
var child = binaryTree.GetChild(i);

if (child != null)
{
queue.Enqueue(child);
}
}
}
}


/// <inheritdoc />
public virtual bool IsLeafNode
{
get
{
return Degree == 0;
}
}

/// <summary>
/// Removes the left child.
/// </summary>
public virtual void RemoveLeft()
{
if (leftSubtree != null)
{
leftSubtree.Parent = null;
leftSubtree = null;
}
}

/// <summary>
/// Removes the left child.
/// </summary>
public virtual void RemoveRight()
{
if (rightSubtree != null)
{
rightSubtree.Parent = null;
rightSubtree = null;
}
}

/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="subtree">The subtree.</param>
/// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception>
/// <exception cref="InvalidOperationException">The <see cref="BinaryTree{T}"/> is full.</exception>
/// <exception cref="ArgumentNullException"><paramref name="subtree"/> is null (Nothing in Visual Basic).</exception>
public void Add(BinaryTree<T> subtree)
{
Guard.ArgumentNotNull(subtree, "subtree");

AddItem(subtree);
}

/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="subtree">The subtree.</param>
/// <remarks>
/// <b>Notes to Inheritors: </b>
/// Derived classes can override this method to change the behavior of the <see cref="Clear"/> method.
/// </remarks>
protected virtual void AddItem(BinaryTree<T> subtree)
{
if (leftSubtree == null)
{
if (subtree.Parent != null)
{
subtree.Parent.Remove(subtree);
}

leftSubtree = subtree;
subtree.Parent = this;
}
else if (rightSubtree == null)
{
if (subtree.Parent != null)
{
subtree.Parent.Remove(subtree);
}

rightSubtree = subtree;
subtree.Parent = this;
}
else
{
throw new InvalidOperationException("This binary tree is full.");
}
}


#endregion

#region Private Members

/// <summary>
/// Finds the maximum height between the child nodes.
/// </summary>
/// <returns>The maximum height of the tree between all paths from this node and all leaf nodes.</returns>
protected virtual int FindMaximumChildHeight()
{
var leftHeight = 0;
var rightHeight = 0;

if (leftSubtree != null)
{
leftHeight = leftSubtree.Height;
}

if (rightSubtree != null)
{
rightHeight = rightSubtree.Height;
}

return leftHeight > rightHeight ? leftHeight : rightHeight;
}

#endregion

#region Operator Overloads

/// <summary>
/// Gets the <see cref="BinaryTree{T}"/> at the specified index.
/// </summary>
public BinaryTree<T> this[int index]
{
get
{
return GetChild(index);
}
}

#endregion

#region ICollection<T> Members

/// <inheritdoc />
public bool IsReadOnly
{
get
{
return false;
}
}

#endregion

#region IEnumerable Members

/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

#endregion

#region Object Members

/// <inheritdoc />
public override string ToString()
{
return data.ToString();
}

#endregion
}
}
Show details Hide details

Change log

r8 by rhanekom on Aug 08, 2009   Diff
- Added ignores for bin and obj
- Added License file and lgpl copy.
- License header updated in all source
files.
Go to: 
Sign in to write a code review

Older revisions

r2 by Simon.Cropp on Aug 07, 2009   Diff
initial port of code from codeplex
All revisions of this file

File info

Size: 19351 bytes, 716 lines
Hosted by Google Code