【问题标题】:Maximum Depth of N-ary Tree - swiftN叉树的最大深度 - swift
【发布时间】:2021-11-22 13:39:39
【问题描述】:

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

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

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

如果你想在 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。不知道为什么...

【问题讨论】:

  • 有什么问题?它不编译吗?错误的结果?运行时崩溃?
  • 对不起。结果不正确。
  • 一个包含输入数据、实际输出和预期输出的独立minimal reproducible example 会很有帮助。
  • 添加输入输出
  • 从一个没有子节点的树开始——你能看出问题吗? – 这是一个逻辑问题,而不是 Swift 问题。

标签: swift recursion tree


【解决方案1】:

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

专业提示。对于这样的 leetcode 风格的问题。最愚蠢/最简单的测试是最好的。

下面这行有两个错误:

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

那就这样吧:

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

我犯了这个错误是因为在?? ?‍♂️ 之后我几乎没有任何算术运算

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多