-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST.cs
98 lines (76 loc) · 2.23 KB
/
BST.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
using System;
using System.Diagnostics;
namespace BinarySearchTree
{
class Node
{
public int value;
public Node left;
public Node right;
}
class Tree
{
public Node insert(Node root, int v)
{
if (root == null)
{
root = new Node();
root.value = v;
}
else if (v < root.value)
{
root.left = insert(root.left, v);
}
else
{
root.right = insert(root.right, v);
}
return root;
}
public void traverse(Node root)
{
if (root == null)
{
return;
}
traverse(root.left);
traverse(root.right);
}
}
class BinarySearchTree
{
static void Main(string[] args)
{
Node root = null;
Tree bst = new Tree();
int SIZE = 2000000;
int[] a = new int[SIZE];
Console.WriteLine("Generating random array with {0} values...", SIZE);
Random random = new Random();
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < SIZE; i++)
{
a[i] = random.Next(10000);
}
watch.Stop();
Console.WriteLine("Done. Took {0} seconds", (double)watch.ElapsedMilliseconds / 1000.0);
Console.WriteLine();
Console.WriteLine("Filling the tree with {0} nodes...", SIZE);
watch = Stopwatch.StartNew();
for (int i = 0; i < SIZE; i++)
{
root = bst.insert(root, a[i]);
}
watch.Stop();
Console.WriteLine("Done. Took {0} seconds", (double)watch.ElapsedMilliseconds / 1000.0);
Console.WriteLine();
Console.WriteLine("Traversing all {0} nodes in tree...", SIZE);
watch = Stopwatch.StartNew();
bst.traverse(root);
watch.Stop();
Console.WriteLine("Done. Took {0} seconds", (double)watch.ElapsedMilliseconds / 1000.0);
Console.WriteLine();
Console.ReadKey();
}
}
}