Created
May 4, 2020 18:44
-
-
Save moaxaca/493236cc56b78aa62bd6fa77e82726fb to your computer and use it in GitHub Desktop.
Iterative Tree Searches
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
package scratch; | |
import java.util.Deque; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.function.Consumer; | |
public class IterativeTreeSearches { | |
static final public class Node<T> { | |
T value; | |
List<Node<T>> children; | |
Node(T value) { | |
this.children = new LinkedList<>(); | |
this.value = value; | |
} | |
public void add(Node<T> node) { | |
this.children.add(node); | |
} | |
} | |
public static void dfs(Node<Integer> root, Consumer<Integer> consumer) { | |
Deque<Node<Integer>> queue = new LinkedList<>(); | |
queue.add(root); | |
while(!queue.isEmpty()) { | |
Node<Integer> node = queue.pop(); | |
Integer value = node.value; | |
consumer.accept(value); | |
for (Node<Integer> nested: node.children) { | |
queue.addFirst(nested); | |
} | |
} | |
} | |
public static void bfs(Node<Integer> root, Consumer<Integer> consumer) { | |
Deque<Node<Integer>> queue = new LinkedList<>(); | |
queue.add(root); | |
while(!queue.isEmpty()) { | |
Node<Integer> node = queue.pop(); | |
Integer value = node.value; | |
consumer.accept(value); | |
for (Node<Integer> nested: node.children) { | |
queue.addLast(nested); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
Node<Integer> root = new Node<>(1); | |
Node<Integer> l2 = new Node<>(2); | |
l2.add(new Node<>(4)); | |
l2.add(new Node<>(5)); | |
Node<Integer> r2 = new Node<>(3); | |
r2.add(new Node<>(6)); | |
r2.add(new Node<>(7)); | |
root.add(l2); | |
root.add(r2); | |
System.out.println("BFS:"); | |
bfs(root, (Integer number) -> System.out.println(number.toString())); | |
System.out.println("DFS:"); | |
dfs(root, (Integer number) -> System.out.println(number.toString())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment