我在操场文件中提取了问题,以使讨论更加容易。我的问题是,我需要找出树中具有最小子节点数的节点的所有值。我没有正确的递归。我的算法的结果为[1,9],但应为:[1,3,9]。有什么想法吗?
import Foundation
class TreeNode{
var children: [TreeNode]?
var value: Int
init( value: Int, children: [TreeNode]?){
self.value = value
self.children = children
}
}
let node11 = TreeNode(value: 11, children: nil)
let node10 = TreeNode(value: 10, children: nil)
let node9 = TreeNode(value: 9, children: [node10, node11])
let node8 = TreeNode(value: 8, children: nil)
let node7 = TreeNode(value: 7, children: [node9])
let node6 = TreeNode(value: 6, children: [node8])
let node5 = TreeNode(value: 5, children:nil)
let node4 = TreeNode(value: 4, children: [node7])
let node3 = TreeNode(value: 3, children: [node5, node6])
let node2 = TreeNode(value: 2, children: [node4])
let node1 = TreeNode(value: 1, children: [node2,node3])
let node0 = TreeNode(value: 0, children: [node1])
func valueOfNodes(minNumberOfChildren: Int, node: TreeNode, tempResult: [Int])->[Int]{
var result = tempResult
guard let children = node.children else{
return result
}
if children.count >= minNumberOfChildren{
result.append(node.value)
}
for child in children{
return valueOfNodes(minNumberOfChildren: minNumberOfChildren, node: child, tempResult: result)
}
return result
}
let result = valueOfNodes(minNumberOfChildren: 2, node: node0, tempResult: [])
print(result)
答案 0 :(得分:1)
您始终只返回第一个孩子的结果:
def getTerm(self,value):
catalog = api.portal.get_tool(name='portal_catalog')
brains = catalog.searchResults({'portal_type':'Organization',
'Title':value,
})
return SimpleTerm(title=brains[0]['Title'],
value=brains[0]['Title'],
)
相反,您需要将它们结合起来
for child in children{
return valueOfNodes(minNumberOfChildren: minNumberOfChildren, node: child, tempResult: result)
}
这种方法终止了尾递归优化,但我认为您不能在此处使用它,因为父级的结果取决于所有子级的结果。