-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search.cs
80 lines (74 loc) · 2.49 KB
/
Search.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace TryLearnedConcepts
{
internal class Search
{
internal static void DepthFirstSearch<T>(BinaryTree<T> binaryTree)
{
Console.WriteLine("Depth First Search");
// create a hashtable of seen
Hashtable seen = new Hashtable();
// create a stack
Stack<BinaryTreeNode<T>> toProcess = new Stack<BinaryTreeNode<T>>();
// push the root
toProcess.Push(binaryTree.Root);
// while stack is not empty
while (toProcess.Count != 0)
{
// pop
var temp = toProcess.Pop();
// check if seen
if (!seen.ContainsKey(temp) && temp != null)
{
// add current to seen
seen.Add(temp, 1);
// add children to stack
if (temp.Right != null)
{
toProcess.Push(temp.Right);
}
if (temp.Left != null)
{
toProcess.Push(temp.Left);
}
// process node
Console.WriteLine(temp.Value);
}
}
}
internal static void BreadthFirstSearch<T>(BinaryTree<T> binaryTree)
{
Console.WriteLine("Breadth First Search");
// create a hashtable of seen
Hashtable seen = new Hashtable();
// create a queue
Queue<BinaryTreeNode<T>> toProcess = new Queue<BinaryTreeNode<T>>();
// enqueue the root
toProcess.Enqueue(binaryTree.Root);
// while queue is not empty
while (toProcess.Count != 0)
{
// dequeue
var temp = toProcess.Dequeue();
// check if seen
if (!seen.ContainsKey(temp))
{
// add children to queue
if (temp.Left != null)
{
toProcess.Enqueue(temp.Left);
}
if (temp.Right != null)
{
toProcess.Enqueue(temp.Right);
}
// process dequeued node
Console.WriteLine(temp.Value);
}
}
}
}
}