我正在尝试对树中的遍历节点执行递归函数
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)。
无论如何,当条件满足时保留返回真...或停止遍历?
好像你在找类似的东西 -
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))