dev*_*r87 20 javascript tree data-structures
我正在努力学习数据结构并实现以下代码,以便在常规树上进行深度优先遍历/应用回调:
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);
}
};
Run Code Online (Sandbox Code Playgroud)
我怎么能改变这一点,而不是先扩大它?这就是Tree Class的样子:
var Tree = function (value) {
var newTree = {};
newTree.value = value;
newTree.children = [];
extend(newTree, treeMethods);
return newTree;
};
Run Code Online (Sandbox Code Playgroud)
Mat*_*ans 47
从根本上说,DFS和BFS之间的区别在于,使用DFS将当前节点的子节点推送到堆栈,因此它们将在其他所有节点之前被弹出和处理,而对于BFS,您将子节点推送到队列的末尾,所以他们将在其他一切之后被弹出和处理.
DFS很容易递归实现,因为您可以将调用堆栈用作堆栈.你不能用BFS做到这一点,因为你需要一个队列.为了使相似性清晰,我们首先将DFS转换为迭代实现:
//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]);
}
}
};
Run Code Online (Sandbox Code Playgroud)
现在是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]);
}
}
};
Run Code Online (Sandbox Code Playgroud)