繁体   English   中英

Swift:确定树中的节点

[英]Swift: Determine nodes in tree

我将我的问题抽象到了一个 Playground 文件中,以便于讨论。 我的问题是我需要找出具有最少子节点的树中节点的所有值。 我没有得到正确的递归。 我的算法的结果是 [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)

你总是只为第一个孩子返回结果:

for child in children{
    return valueOfNodes(minNumberOfChildren: minNumberOfChildren, node: child, tempResult: result)
}

相反,您需要将它们结合起来

let childrenResult = children.flatMap { child in
    return valueOfNodes(minNumberOfChildren: minNumberOfChildren, node: child, tempResult: [])
}
result.append(contentsOf: childrenResult)

这种方法会扼杀尾递归优化,但我认为您不能在这里使用它,因为父级的结果取决于所有子级的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM