Daily Tech Journal

Vinu Nair
Jun 2, 2021

2-June-2021

Felt the need to improve my coding skills and thought to start off with depth-first search.

Depth First Search

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

Input — Node is a class with a name field and optional children's array.

Output — Return an array in depth-first order.

public List<String> depthFirstSearch(List<String> array) {
array.add(node.name);
depthFirstSearch(array,node);
return array;
}

public void depthFirstSearch(List<String> array, Node node) {
for(int i = 0; i < node.children.size(); i++) {
array.add(node.children.get(i).name);
depthFirstSearch(array,node.children.get(i));
}
}

--

--