Depth-First Search (DFS)
- Basically recursive traversal, as we've seen (like inorder)
- But what if large and want to preserve runtime stack space?
/**
* Returns the first element found that is equal to elem in the tree
* rooted at node. Uses a depth-first search. If no equal is found,
* returns null.
*/
public static <E> E dfs(E elem, TreeNode<E> node) {
Deque<TreeNode<E>> stack = new ArrayDeque<TreeNode<E>>();
stack.push(node);
while (!stack.isEmpty()) {
TreeNode<E> curr = stack.pop();
System.out.println(curr.getData());
if (curr.getData().equals(elem)) {
//found it
return elem;
}
if (curr.getRight() != null) {
stack.push(curr.getRight());
}
if (curr.getLeft() != null) {
stack.push(curr.getLeft());
}
}
//out of nodes, but never returned from in loop
return null;
}
Breadth-First Search (BFS)
- Interestingly: just like DFS, but with a Queue instead.
/**
* Returns the first element found that is equal to elem in the tree
* rooted at node. Uses a breadth-first search. If no equal is found,
* returns null.
*/
public static <E> E bfs(E elem, TreeNode<E> node) {
Queue<TreeNode<E>> queue = new ArrayDeque<TreeNode<E>>();
queue.offer(node);
while (!queue.isEmpty()) {
TreeNode<E> curr = queue.poll();
System.out.println(curr.getData());
if (curr.getData().equals(elem)) {
//found it
return elem;
}
if (curr.getLeft() != null) {
queue.offer(curr.getLeft());
}
if (curr.getRight() != null) {
queue.offer(curr.getRight());
}
}
//out of nodes, but never returned from in loop
return null;
}