Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created December 18, 2018 09:34
Show Gist options
  • Save nichtemna/4538785aafac7d6c2d975d3ee3e45619 to your computer and use it in GitHub Desktop.
Save nichtemna/4538785aafac7d6c2d975d3ee3e45619 to your computer and use it in GitHub Desktop.
DFS in Java
public class Main {
public static void main(String[] args) {
Tree tree = initiateTree();
tree.printTree();
int searchValue = 10;
Node resultNode = tree.dfs(searchValue);
if (resultNode == null) {
System.out.print("No node found with value " + searchValue);
} else {
System.out.print("Found node with value " + searchValue);
}
}
private static Tree initiateTree() {
Tree tree = new Tree(1);
tree.addNode(1, 2);
tree.addNode(1, 3);
tree.addNode(1, 4);
tree.addNode(2, 5);
tree.addNode(2, 6);
tree.addNode(3, 7);
tree.addNode(3, 8);
return tree;
}
}
class Node {
final int value;
final List<Node> nodes = new ArrayList<>();
Node(int value) {
this.value = value;
}
void addChild(Node node) {
nodes.add(node);
}
}
class Tree {
private final Node head;
Tree(int headNodeValue) {
this.head = new Node(headNodeValue);
}
Node dfs(int value) {
Deque<Node> stack = new LinkedList<>();
stack.addFirst(head);
while (!stack.isEmpty()) {
Node node = stack.removeFirst();
if (node.value == value) {
return node;
}
for (Node child : node.nodes) {
stack.addFirst(child);
}
}
return null;
}
void addNode(int parentValue, int childValue) {
Node parentNode = dfs(parentValue);
if (parentNode != null) {
parentNode.addChild(new Node(childValue));
}
}
void printTree() {
Deque<Node> queue = new LinkedList<>();
queue.addFirst(head);
while (!queue.isEmpty()) {
Node node = queue.removeLast();
for (Node child : node.nodes) {
queue.addFirst(child);
}
System.out.println(node.value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment