【问题标题】:Refactor Code to Tail-Recursion将代码重构为尾递归
【发布时间】:2019-01-10 09:14:30
【问题描述】:

我有一个函数可以通过“节点”,这些“节点”有一个键和它们自己的 nodes 数组。我还有一组允许的键。目标很简单:如果一个节点有一个允许的键,或者一个子节点有一个允许的键,则保留它,否则,删除它。当前的解决方案如下所示:

var allowedKeys = ['x', 'y', 'z'];

var nodes = [{
    key: 'x',
    nodes: []
  },
  {
    key: 'b',
    nodes: [{
        key: 'y',
        nodes: []
      },
      {
        key: 'lol',
        nodes: []
      },
    ]
  },
  {
    key: 'c'
  },
  {
    key: 'd',
    nodes: []
  },
  {
    key: 'e',
    nodes: [{
        key: 't',
        nodes: [{
          key: 'z',
          nodes: []
        }]
      },
      {
        key: 'r',
        nodes: []
      },
    ]
  },
  {
    key: 'f',
    nodes: []
  }

];

function hasChildNodes(node) {
  var hasChildNodes = node.hasOwnProperty('nodes') && node.nodes.length > 0;
  return hasChildNodes;
}

function removeUnnecessaryNodes(nodes, allowedKeys) {
  nodes.forEach(node => {
    if (hasChildNodes(node)) {
      node.nodes = removeUnnecessaryNodes(node.nodes, allowedKeys);
    }
  });

  nodes = nodes.filter(node => allowedKeys.includes(node.key) || hasChildNodes(node));

  return nodes;
}


var filteredNodes = removeUnnecessaryNodes(nodes, allowedKeys);
console.log(filteredNodes);

我想重构它以使用尾递归以避免炸毁堆栈。我开始觉得这是不可能的。

附:我意识到大多数 javascript 实现不使用尾递归优化,幽默。

【问题讨论】:

  • 您可以转换为使用async 代码,即使您没有任何异步方法,async 的一个优点是调用堆栈可以在递归期间清除。
  • 这可以重写以使用显式堆栈来模拟递归。

标签: javascript recursion stack tail-recursion


【解决方案1】:

根据我的评论,我想尝试一个堆栈版本。它没有我希望的那么干净,但我想我还是会发布它,希望它能在某些方面有所启发。

var nodes = [{
    key: 'x',
    nodes: []
  },
  {
    key: 'b',
    nodes: [{
        key: 'y',
        nodes: []
      },
      {
        key: 'lol',
        nodes: []
      },
    ]
  },
  {
    key: 'c'
  },
  {
    key: 'd',
    nodes: []
  },
  {
    key: 'e',
    nodes: [{
        key: 't',
        nodes: [{
          key: 'z',
          nodes: []
        }]
      },
      {
        key: 'r',
        nodes: []
      },
    ]
  },
  {
    key: 'f',
    nodes: []
  }
];

var allowedKeys = ['x', 'y', 'z'];

const removeUnnecessaryNodes = (nodes, allowedKeys) => {
  const allowed = new Set(allowedKeys);
  const root = {nodes: nodes};
  const stack = [root];
  
  while (stack.length) {
    let curr = stack.pop();
    
    if (curr.nodes && curr.nodes.length) {

      // non-empty node, push children on stack
      curr.nodes.forEach(e => {
        e.parent = curr;
      	stack.push(e);
      });
    }
    else if (!allowed.has(curr.key)) {

      // this is a disallowed leaf; remove it
      let p = curr.parent;

      if (p) {
        p.nodes = p.nodes.filter(e => e !== curr); // O(n)
      }

      // move up the structure, pruning dead ancestors
      while (p && !p.nodes.length && !allowed.has(p.key)) {
        curr = p;
        p = curr.parent;

        if (p) {
          p.nodes = p.nodes.filter(e => e !== curr); // O(n)
        }
      }
    }
  }

  // clean up temporary parent keys
  stack.push(root);
  
  while (stack.length) {
    const curr = stack.pop();
    
    if (curr.nodes) {
      curr.nodes.forEach(e => {
        delete e.parent;
      	stack.push(e);
      });
    }
  }
  
  return root.nodes;
};

var filteredNodes = removeUnnecessaryNodes(nodes, allowedKeys);
console.log(JSON.stringify(filteredNodes, null, 4));

说明

准备工作包括将nodes 键添加到外部数组并将allowedKeys 转换为一组以进行快速查找。然后,DFS 结构,为每个键分配新的parent 属性并将子项压入堆栈。如果到达叶节点并且其键被禁止,则将其从其父节点列表中取消链接。如果父列表随后为空并且父节点的键被禁止,则也取消链接并重复直到到达有效的祖先。最后,对结构执行另一个 DFS 以删除临时父属性。

需要改进的地方

我尝试使用一个对象来存储父属性,但遇到了比较/重复问题,于是求助于链表方法。我确信可以解决,节省第二次清理 DFS 和潜在的密钥冲突。

此外,节点列表过滤过程是 O(n) 并且可以通过散列或至少在找到子密钥后提前救助来改进。

我确定还有其他人!我很想听听反馈或听听它在大输入上的表现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多