Skip to content

Commit dd29350

Browse files
committed
Added BinarySearchTree.cs
1 parent eb83b47 commit dd29350

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
using System;
2+
3+
namespace DataStructures
4+
{
5+
class BinarySearchTree<T> where T : IComparable<T>
6+
{
7+
public BinarySearchTree<T> Left;
8+
public BinarySearchTree<T> Right;
9+
10+
public T Value;
11+
12+
public BinarySearchTree(T value)
13+
{
14+
Value = value;
15+
}
16+
17+
public void Add(T newValue)
18+
{
19+
if (newValue.CompareTo(Value) == 0) throw new DuplicateValueInSetException();
20+
21+
if (newValue.CompareTo(Value) < 0)
22+
{
23+
if (Left == null)
24+
{
25+
Left = new BinarySearchTree<T>(newValue);
26+
}
27+
else
28+
{
29+
Left.Add(newValue);
30+
}
31+
32+
}
33+
else
34+
{
35+
if (Right == null)
36+
{
37+
Right = new BinarySearchTree<T>(newValue);
38+
}
39+
else
40+
{
41+
Right.Add(newValue);
42+
}
43+
}
44+
}
45+
46+
public static void TestBST()
47+
{
48+
var bst = new BinarySearchTree<int>(69);
49+
bst.Add(42);
50+
bst.Add(14);
51+
bst.Add(37);
52+
bst.Add(46);
53+
bst.Add(13);
54+
bst.Add(53);
55+
bst.Add(78);
56+
bst.Add(1);
57+
bst.Add(51);
58+
bst.Add(5);
59+
bst.Add(18);
60+
bst.Add(8);
61+
62+
bst.ToList().ForEach(Console.WriteLine);
63+
}
64+
}
65+
}

0 commit comments

Comments
 (0)