N 叉树的最大深度 - swift

Maximum Depth of N-ary Tree - swift

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

我已经通过其他方式解决了这个问题。我只是想通过这段代码来解决它。试图弄清楚什么是不正确的。它目前 returns 不正确的结果:

class Solution {
    func maxDepth(_ root: Node?) -> Int {
        guard let node = root else { return 0 }
        return node.children.map(maxDepth).max() ?? 0 + 1
    }
} 

Helper class 如果你想在 Xcode 上测试这个:

class Node {
    var value: Int
    var children: [Node] = []
    weak var parent: Node?
    
    init(value: Int) {
        self.value = value
    }
    
    func add(child: Node) {
        children.append(child)
        child.parent = self
    }
}

示例:

let one = Node(value: 1)
let two = Node(value: 2)
let three = Node(value: 3)

one.add(child: two)
two.add(child: three)
print("res", maxDepth(one)) // returns: 2. Expected: 3

实际上我总是回来 2。不知道为什么...

感谢 Martin 帮我解决了这个问题。

专业提示。对于此类 leetcode 风格的问题。 dumbest/simplest 测试是最好的。

下面这行有 2 个错误:

return node.children.map(maxDepth).max() ?? 1 + 1
  • ?? 默认为 0 + 1。将 ?? 括在括号
  • 默认值实际上应该是0。不是 1

那就这样吧:

return (node.children.map(maxDepth).max() ?? 0) + 1

我犯了那个错误,因为我在?? ‍♂️

之后几乎没有任何算术运算