-
-
Notifications
You must be signed in to change notification settings - Fork 360
/
Copy pathExample.cs
113 lines (96 loc) · 2.55 KB
/
Example.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
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class BinarySearchTree<T> where T : IComparable
{
class Node
{
public T Value { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public static object ToData(Node node)
{
if (node == null) return null;
return new
{
data = node.Value,
left = Node.ToData(node.Left),
right = Node.ToData(node.Right)
};
}
public IEnumerable<T> GetOrderedValues()
{
if (Left != null)
{
foreach(var value in Left.GetOrderedValues())
{
yield return value;
}
}
yield return Value;
if (Right != null)
{
foreach(var value in Right.GetOrderedValues())
{
yield return value;
}
}
}
}
Node head;
public int Count { get; private set; }
public void Add(T value)
{
Count++;
if (head == null) {
head = new Node { Value = value };
return;
}
var node = head;
while(true)
{
if (node.Value.CompareTo(value) >= 0)
{
if (node.Left == null)
{
node.Left = new Node { Value = value };
break;
}
node = node.Left;
} else {
if (node.Right == null)
{
node.Right = new Node { Value = value };
break;
}
node = node.Right;
}
}
}
public bool Contains(T value)
{
var node = head;
while(node != null)
{
if (node.Value.CompareTo(value) == 0) { return true; }
if (node.Value.CompareTo(value) < 0) { node = node.Left; }
else { node = node.Right; }
}
return false;
}
public string ToJson()
{
if (head == null) return null;
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
};
var data = Node.ToData(head);
return JsonConvert.SerializeObject(data, settings);
}
public IEnumerable<T> GetOrderedValues()
{
if (head == null) return new T[0];
return head.GetOrderedValues();
}
}