Depth-First-Search (DFS)— Competitive Programming with Time and Space Complexity

Question

You’re given a Node class that has a name and an array of optional children nodes. When put together, nodes form an acyclic tree-like structure.

Implement the depthFirstSearch method on the Node class, which takes in an empty array, traverses the tree using the Depth-first Search approach (specifically navigating the tree from left to right), stores all of the nodes’ names in the input array, and returns it.

Sample Input:

Input Graph

Sample Output:

[“A”, “B”, “E”, “F”, “I”, “J”, “C”, “D”, “G”, “K”, “H”]

Node Class:

public class Node
{
public string name;
public List<Node> children = new List<Node>();
public Node(string name)
{
this.name = name;
}
public Node AddChild(string name)
{
Node child = new Node(name);
children.Add(child);
return this;
}
}

Solution

private List<string> DepthFirstSearch(Node node, List<string> dfs)
{
dfs.Add(node.name);
foreach (var child in node.children)
{
DepthFirstSearch(child, dfs);
}
return dfs;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store