Created
November 12, 2012 07:26
-
-
Save elicwhite/4057988 to your computer and use it in GitHub Desktop.
Breadth First Traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Node node = new Node(5); | |
var n2 = new Node(2); | |
node.Children.Add(n2); | |
var n4 = new Node(16); | |
n2.Children.Add(n4); | |
var n3 = new Node(-1); | |
n4.Children.Add(n3); | |
var n5 = new Node(-6); | |
n2.Children.Add(n5); | |
/* | |
5 | |
2 | |
16 | |
-6 | |
-1 | |
*/ | |
breadthFirst(node); | |
Console.ReadKey(); | |
return; | |
} | |
public static void breadthFirst(Node root) | |
{ | |
Queue<Node> nodes = new Queue<Node>(); | |
nodeHelper(nodes, root); | |
} | |
public static void nodeHelper(Queue<Node> q, Node node) | |
{ | |
Console.WriteLine(node.data); | |
foreach (Node n in node.Children) | |
{ | |
q.Enqueue(n); | |
} | |
if (q.Count > 0) | |
{ | |
nodeHelper(q, q.Dequeue()); | |
} | |
} | |
} | |
class Node | |
{ | |
public int data; | |
public List<Node> Children; | |
public Node(int d) | |
{ | |
data = d; | |
Children = new List<Node>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment