【问题标题】:Convert a recursive method to loop method将递归方法转换为循环方法
【发布时间】:2020-10-01 02:12:48
【问题描述】:
async function treeTraverser(userId) {
if (userId !== null) {
const user = await User.findById(userId).select("-password");
graphUsers.push(user);
treeTraverser(user.directions.left);
treeTraverser(user.directions.right);
}
}
我想把这个函数转换成循环函数。
user.directions
是一个包含其他用户ID的对象
user.directions: {
left: someId,
right: someId
}
我要感谢优秀的开发者社区。p>
【问题讨论】:
标签:
javascript
node.js
loops
recursion
【解决方案1】:
async function treeTraverser(userId) {
if (userId !== null) {
const user = await User.findById(userId).select("-password");
graphUsers.push(user);
}
}
Object.keys(user.directions).forEach((key) => {
treeTraverser(user.direction[key])
})
【解决方案2】:
async function iterativePreOrderTraverser(userId) {
if (userId === null) return;
const nodeStack = [];
nodeStack.push(userId);
while (nodeStack.length > 0) {
let poppedUserId = nodeStack.pop();
const user = await User.findById(poppedUserId);
graphUsers.push(user);
if (user.directions.right !== null) {
nodeStack.push(user.directions.right);
}
if (user.directions.left !== null) {
nodeStack.push(user.directions.left);
}
}
基本上我的问题包含一个前序树遍历代码。所以我在网上搜索并在Geek For Geeks 上找到了一个解决方案,它通过循环解决了这个问题。它不包含 javascript 代码,但我可以将 python 代码转换为 javascript 代码。