I have been reading the following article: https://code.tutsplus.com/articles/data-structures-with-javascript-tree--cms-23393
This sets up the following classes and methods.
function Node(data) {
this.data = data;
this.parent = null;
this.children = [];
}
function Tree(data) {
var node = new Node(data);
this._root = node;
}
Tree.prototype.traverseDF = function(callback) {
(function recurse(currentNode) {
for (var i = 0, length = currentNode.children.length; i < length; i++) {
recurse(currentNode.children[i]);
}
callback(currentNode);
})(this._root);
};
var tree = new Tree('one');
tree._root.children.push(new Node('two'));
tree._root.children[0].parent = tree;
tree._root.children.push(new Node('three'));
tree._root.children[1].parent = tree;
tree._root.children.push(new Node('four'));
tree._root.children[2].parent = tree;
tree._root.children[0].children.push(new Node('five'));
tree._root.children[0].children[0].parent = tree._root.children[0];
tree._root.children[0].children.push(new Node('six'));
tree._root.children[0].children[1].parent = tree._root.children[0];
tree._root.children[2].children.push(new Node('seven'));
tree._root.children[2].children[0].parent = tree._root.children[2];
This tree looks like
one
├── two
│ ├── five
│ └── six
├── three
└── four
└── seven
So when we finally make our traversal call
tree.traverseDF(function(node) {
console.log(node.data)
});
It returns:
five
six
two
three
seven
four
one
This broke my understanding of "depth first". If you google depth first, wikipedia has the following image:
Under this picture it feels like the previous code should print:
one
two
five
six
According to wikipedia:
One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking
The current implementation in this question, actually prints starting from the bottom, youngest children and moves up instead of top to bottom how its defined by wikipedia. Can anyone help me understand what I am missing?
