javascript - Checking if this is a Stack/DFS
问题描述
I'm doing some work that involves grabbing some specific nodes in a tree-like structure. My colleague claims that my implementation, which we are trying to use a stack and a DFS algorithm, is not that.
Here is my implementation of using a stack to create a basic DFS algorithm:
const findMatchingElements = (node, name, result) => {
for(const child of node.children) {
findMatchingElements(child, name, result)
}
if(node.name === name) result.push(node)
return result
}
const getElements = (tree, name) => {
return findMatchingElements(tree, name, [])
}
getElements(obj, 'foo')
And a sample input:
const obj = {
id: 1,
name: 'foo',
children: [
{
id: 45,
name: 'bar',
children: [
{
id: 859,
name: 'bar',
children: []
}
]
},
{
id: 67,
name: 'foo',
children: [
{
id: 456,
name: 'bar',
children: []
},
{
id: 653,
name: 'foo',
children: []
}
]
}
]
}
I am getting my expected output:
[ { id: 653, name: 'foo', children: [] },
{ id: 67, name: 'foo', children: [ [Object], [Object] ] },
{ id: 1, name: 'foo', children: [ [Object], [Object] ] } ]
In the order I expect as well, but my colleague for some reason does not think this is a proper stack implementation. Am I missing something? Is it because of the way the final answer is printed out? To me, this feels like it is a stack.
解决方案
I'm a bit confused about what you're disagreeing about here but that output looks like a stack to me if you agree that it's LIFO once the client starts using it. Right now it's just a JavaScript array, but if you start pushing and popping on it, and only doing that, then it's a JavaScript implementation of a stack.
推荐阅读
- typescript - 如何解决 nuxt 中的这些 cookie 相关警告?
- nativescript - NativeScript Vue:在哪里存储 API 密钥和其他凭据?
- python - 如何使用 pptx python 将 ppt 幻灯片导出为图像
- javascript - 为什么我们要以 express 形式返回状态码和响应?
- node.js - EdgeNgram autocomplete_filter 对前缀搜索有意义吗?
- c++ - c++中变量前面的星号是什么?
- javascript - 在异步函数中进行测试。测试通过什么时候应该失败
- asp.net - 我有一个带有三个表单标签的视图。如何在控制器中分别处理每个表单?
- powershell - 将 ProxyAddresses 添加到单独的脚本
- python - 冗余图例:Matplotlib