Last active
August 28, 2019 00:30
-
-
Save riyadparvez/5915102 to your computer and use it in GitHub Desktop.
Implementation of depth first search or DFS in C#.
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
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