Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

breadth-first traversal of a tree in javascript

Tags:

I am trying to learn data structures well and implemented the following code for a depth-first traversal/application of a callback on a regular tree:

Tree.prototype.traverse = function (callback) {   callback(this.value);    if (!this.children) {     return;   }   for (var i = 0; i < this.children.length; i++) {     var child = this.children[i];     child.traverse(callback);   } }; 

How could I change this to make it breadth first instead? This is what the Tree Class looks like:

var Tree = function (value) {   var newTree = {};    newTree.value = value;   newTree.children = [];   extend(newTree, treeMethods);    return newTree; }; 
like image 412
devdropper87 Avatar asked Nov 13 '15 22:11

devdropper87


People also ask

What is breadth first tree traversal?

Breadth-first search (BFS) is an algorithm for searching a tree data structure for a node that satisfies a given property. It starts at the tree root and explores all nodes at the present depth prior to moving on to the nodes at the next depth level.

What is breadth first search Javascript?

A breadth first search moves from the root node down to its first child, then immediately backtracks to the root node and traverses any additional child nodes.

What are Traversals in Javascript?

What is Traversing? jQuery traversing, which means "move through", are used to "find" (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire. The image below illustrates an HTML page as a tree (DOM tree).


1 Answers

Fundamentally, the difference between DFS and BFS is that with a DFS you push the children of the current node onto a stack, so they will be popped and processed before everything else, while for BFS you push the children onto the end of a queue, so they will be popped and processed after everything else.

DFS is easy to implement recursively because you can use the call stack as the stack. You can't do that with BFS, because you need a queue. Just to make the similarity clear, lets convert your DFS to an iterative implementation first:

//DFS Tree.prototype.traverse = function (callback) {   var stack=[this];   var n;    while(stack.length>0) {      n = stack.pop();     callback(n.value);      if (!n.children) {       continue;     }      for (var i = n.children.length-1; i>=0; i--) {        stack.push(n.children[i]);     }   } }; 

And now BFS

//BFS Tree.prototype.traverse = function (callback) {   var queue=[this];   var n;    while(queue.length>0) {      n = queue.shift();     callback(n.value);      if (!n.children) {       continue;     }      for (var i = 0; i< n.children.length; i++) {        queue.push(n.children[i]);     }   } }; 
like image 121
Matt Timmermans Avatar answered Oct 04 '22 12:10

Matt Timmermans