It is easy to do DFS using recursion:
function dfs(tree, fn, level) {
fn(tree, level)
tree.children.forEach(function(child){
dfs(child, fn, level + 1)
})
}
However every example I have seen of BFS uses a queue and is iterative rather than recursive. Wondering if there is any way to define a recursive BFS algorithm.
Iterative BFS While one can write BFS recursively ---recursion and iteration are equally powerful--- it is awkward, and no one does it, practically speaking.
Depth First Traversals are typically recursive and recursive code requires function call overheads. The most important points is, BFS starts visiting nodes from root while DFS starts visiting nodes from leaves. So if our problem is to search something that is more likely to closer to root, we would prefer BFS.
Recursion is a programming pattern or concept embedded in many programming languages, and JavaScript is not left out. It is a feature used in creating a function that keeps calling itself but with a smaller input every consecutive time until the code's desired result from the start is achieved.
Depth First Search (DFS)The DFS algorithm is a recursive algorithm that uses the idea of backtracking.
If sibling nodes can be ordered and have information or a way to retrieve information about their siblings, we can execute in the order of a breadth first search. Clearly, with abstract data, building the tree as we go, like calculating a subsequent chess move, this may impossible or prohibitively complicated. Tree data structures, however, could be built with provisions for sibling information.
Here's an example with dummy 'sibling' and 'done' functions. If we're not guaranteed each node has children, we may want an extra parameter to record the last seen child. Note that 'next sibling' could be akin to a linked list but could also be implemented as a method of calculating what the next sibling is based on known information.
function bfs(tree, fn) {
fn(tree);
if (tree.done) return;
if (tree.isLastSibling)
bfs(tree.children.firstSibling(), fn);
else
bfs(tree.nextSibling(), fn);
}
var c4 = {
val: 'c4',
isLastSibling: true,
done: true
}
var c3 = {
val: 'c3',
nextSibling: () => c4
}
var c2 = {
val: 'c2',
nextSibling: () => c3
}
var c1 = {
val: 'c1',
nextSibling: () => c2
}
var b2 = {
val: 'b2',
isLastSibling: true,
children: {firstSibling: () => c1}
}
var b1 = {
val: 'b1',
nextSibling: () => b2
}
var a = {
val: 'a',
isLastSibling: true,
children: {firstSibling: () => b1}
}
bfs(a, tree => console.log(tree.val))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With