From bc710f263f477d633798c9b357ce7f4178baddbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Tue, 11 Jan 2022 14:45:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20104.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6=20Swift?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 77 +++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 85b41548..7038598b 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -653,5 +653,82 @@ int maxDepth(struct TreeNode* root){ } ``` +## Swift + +>二叉树最大深度 +```swift +// 递归 - 后序 +func maxDepth1(_ root: TreeNode?) -> Int { + return _maxDepth1(root) +} +func _maxDepth1(_ root: TreeNode?) -> Int { + if root == nil { + return 0 + } + let leftDepth = _maxDepth1(root!.left) + let rightDepth = _maxDepth1(root!.right) + return 1 + max(leftDepth, rightDepth) +} + +// 层序 +func maxDepth(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + var queue = [TreeNode]() + queue.append(root) + var res: Int = 0 + while !queue.isEmpty { + res += 1 + for _ in 0 ..< queue.count { + let node = queue.removeFirst() + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + } + return res +} +``` + +>N叉树最大深度 +```swift +// 递归 +func maxDepth(_ root: Node?) -> Int { + guard let root = root else { + return 0 + } + var depth = 0 + for node in root.children { + depth = max(depth, maxDepth(node)) + } + return depth + 1 +} + +// 迭代-层序遍历 +func maxDepth1(_ root: Node?) -> Int { + guard let root = root else { + return 0 + } + var depth = 0 + var queue = [Node]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + depth += 1 + for _ in 0 ..< size { + let node = queue.removeFirst() + for child in node.children { + queue.append(child) + } + } + } + return depth +} +``` + -----------------------