Swift 二叉树最大深度 - 常见错误解析与修正
/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right: TreeNode?\n * public init() { self.val = 0; self.left = nil; self.right = nil; }\n * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }\n * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {\n * self.val = val\n * self.left = left\n * self.right = right\n * }\n * }\n */\nclass Solution {\n func maxDepth(_ root: TreeNode?) -> Int {\n\t\tif root == nil {\n return 0\n }\n return max(maxDepth(root.left), maxDepth(root.right)) + 1\n }\n}//这段代码的报错可能是因为在Swift中,可选类型(Optional)的语法是使用“?”而不是“?)”。因此,在代码中将“root.left?”和“root.right?”改为“root.left”和“root.right”应该可以解决问题。修改后的代码如下:\n\nswift\nclass Solution {\n func maxDepth(_ root: TreeNode?) -> Int {\n if root == nil {\n return 0\n }\n return max(maxDepth(root.left), maxDepth(root.right)) + 1\n }\n}\n
原文地址: https://www.cveoy.top/t/topic/qflf 著作权归作者所有。请勿转载和采集!