func maxDepth(_ root: TreeNode?) -> Int {
guard let tree = root else { return 0 }
if tree.left == nil, tree.right == nil { return 1 }
return max(maxDepth(tree.left), maxDepth(tree.right)) + 1
}
2.2 非递归
func maxDepth(_ root: TreeNode?) -> Int {
var deep = 0
guard let root = root else { return deep }
var queue: [TreeNode] = [root]
var currentLevelCount = 1
var nextLevelCount = 0
while queue.isEmpty == false {
let current = queue.removeFirst()
currentLevelCount -= 1
if let left = current.left {
queue.append(left)
nextLevelCount += 1
}
if let right = current.right {
queue.append(right)
nextLevelCount += 1
}
if currentLevelCount == 0 {
deep += 1
currentLevelCount = nextLevelCount
nextLevelCount = 0
}
}
return deep
}