-
Notifications
You must be signed in to change notification settings - Fork 55
/
00.BasicBFSAndDFS.cs
79 lines (71 loc) · 1.7 KB
/
00.BasicBFSAndDFS.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
//implement basic BFS and DFS on a bianry tree
using System;
using System.Collections.Generic;
using System.Collections;
namespace BFSAndDFS
{
public class TreeNode
{
public TreeNode left{ get; set;}
public TreeNode right{get;set;}
public int value{ get; private set;}
public TreeNode(int value)
{
this.value = value;
this.left = null;
this.right = null;
}
}
public class SearchTree
{
public static void DFS(TreeNode root)
{
if (root == null)
return;
Console.WriteLine (root.value);
DFS (root.left);
DFS (root.right);
}
public static void BFS(TreeNode root) // BFS == using a queue!!!!
{
Queue<TreeNode> nodeQueue = new Queue<TreeNode> ();
Console.WriteLine (root.value);
nodeQueue.Enqueue (root);
while (nodeQueue.Count != 0) {
TreeNode temp = nodeQueue.Dequeue ();
if (temp.left != null) {
Console.WriteLine (temp.left.value);
nodeQueue.Enqueue (temp.left);
}
if (temp.right != null) {
Console.WriteLine (temp.right.value);
nodeQueue.Enqueue (temp.right);
}
}
}
}
class MainClass
{
public static void Main (string[] args)
{
//construct a simple binary tree using treenodes
TreeNode Node1 = new TreeNode (3);
TreeNode Node2 = new TreeNode (9);
TreeNode Node3 = new TreeNode (20);
TreeNode Node4 = new TreeNode (15);
TreeNode Node5 = new TreeNode (17);
TreeNode Node6 = new TreeNode (11);
TreeNode Node7 = new TreeNode (13);
TreeNode Node8 = new TreeNode (71);
Node1.left = Node2;
Node1.right = Node3;
Node3.left = Node4;
Node3.right = Node5;
Node4.left = Node6;
Node4.right = Node7;
Node5.left = Node8;
SearchTree.BFS (Node1);
SearchTree.DFS (Node1);
}
}
}