Javascript 递归函数没有返回我想要的结果(树)

问题描述 投票:0回答:1

我正在尝试对树中的遍历节点执行递归函数

  • 不是二叉树,一个父母可以有两个以上的孩子。因此,这里使用了 for 循环或 forEach ..
  • 如果节点具有特定属性,则返回 true
  traversalNodeTreeWithUrn(root, urn): boolean {
    const nodeList = root;
    for(let i = 0; i < nodeList.length; i++) {
      const site = nodeList[i].childSite;    
      if(site.urn === urn) {
        return true;      
      } 
      else { 
        return this.traversalNodeTreeWithUrn(site,  urn);
      }
    }
    return false;

问题是递归的,在 FOUND 返回 true 之后,它会继续下去,直到所有节点都被访问过,然后返回最终值(在我的例子中总是返回 false)。

无论如何,当条件满足时保留返回真...或停止遍历?

javascript recursion tree-traversal
1个回答
1
投票

好像你在找类似的东西 -

function nodeHasUrn(node, urn) {
  if (node.urn === urn) return true
  for (const child of node.children)
    if (nodeHasUrn(child, urn)) return true
  return false
}

这适用于 -

的树形
{
  urn: 1,
  children: [
    { urn: 2 },
    { urn: 3 },
    {
      urn: 4,
      children: [
       { urn: 5 },
       { urn: 6 },
       ...
      ]
    }
  ]
}

这是一个功能演示 -

function nodeHasUrn(node, urn) {
  if (node.urn === urn) return true
  for (const child of node.children ?? [])
    if (nodeHasUrn(child, urn)) return true
  return false
}

const tree = {
  urn: 1,
  children: [
    { urn: 2 },
    { urn: 3 },
    {
      urn: 4,
      children: [
       { urn: 5 },
       { urn: 6 },
      ]
    }
  ]
}

console.log(nodeHasUrn(tree, 5)) // true
console.log(nodeHasUrn(tree, 99)) // false

递归是函数式风格的继承,因此将它与函数式风格一起使用通常会产生最好的结果。考虑将

nodeHasUrn
写成纯函数表达式 -

const nodeHasUrn = ({ urn, children = [] }, match) =>
  urn === match
    ? true
    : children.some(child =>
        nodeHasUrn(child, match)
      )

这和说一样-

const nodeHasUrn = ({ urn, children = [] }, match) =>
  urn === match || children.some(child => nodeHasUrn(child, match))
© www.soinside.com 2019 - 2024. All rights reserved.