Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Last active August 28, 2019 00:30
Show Gist options
  • Save riyadparvez/5915102 to your computer and use it in GitHub Desktop.
Save riyadparvez/5915102 to your computer and use it in GitHub Desktop.
Implementation of depth first search or DFS in C#.
public class Tree<K, V>
where K : class, IComparable<K>
where V : class
{
private Node<K, V> root;
public V DFS(K key)
{
Stack<Node<K, V>> stack = new Stack<Node<K, V>>();
while(stack.Any())
{
var node = stack.Pop();
if(node.key == key)
{
return node.value;
}
foreach (var child in node.children)
{
stack.Push(child);
}
}
return default(V);
}
private class Node<K, V>
where K : class, IComparable<K>
where V : class
{
public K key;
public V value;
public Node<K, V>[] children;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment