【问题标题】: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 代码。

      【讨论】:

        猜你喜欢
        • 2015-01-08
        • 2017-10-26
        • 2017-02-28
        • 2012-12-29
        • 2021-08-09
        • 1970-01-01
        • 1970-01-01
        • 2010-10-10
        • 1970-01-01
        相关资源
        最近更新 更多