-
-
Save scalvert/5da1bc8fcb8d10a535c7 to your computer and use it in GitHub Desktop.
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 DepthFirstSearch(K key) | |
{ | |
Stack<Node<K, V>> stack = new Stack<Node<K, V>>(); | |
root.Visited = true; | |
stack.Push(root); | |
while(stack.Any()) | |
{ | |
var node = stack.Pop(); | |
if (node.Key == key) | |
{ | |
return node.Value; | |
} | |
foreach (var child in node.GetAdjacentUnvisitedNodes()) | |
{ | |
child.Visited = true; | |
stack.Push(child); | |
} | |
} | |
return default(V); | |
} | |
private class Node<K, V> | |
where K : class, IComparable<K> | |
where V : class | |
{ | |
public K Key { get; set; } | |
public V Value { get; set; } | |
public bool Visited { get; set; } | |
public IList<Node<K, V>> Nodes { get; set; } | |
public IList<Node<K, V>> GetAdjacentUnvisitedNodes() | |
{ | |
return this.Nodes.Where(n => !n.Visited); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment