提问者:小点点

将递归方法转换为循环方法


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
}

我将感谢惊人的开发人员社区。


共2个答案

匿名用户

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])
})

匿名用户

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解决方案,它通过循环解决了这个问题。 它不包含javascript代码,但我可以将python代码转换为javascript代码。