From 26c7fd202afc2aac492c2db589a3c4af5af3fcf3 Mon Sep 17 00:00:00 2001 From: YDLIN <1924723909@qq.com> Date: Sat, 22 Jan 2022 11:38:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20513.=20=E6=89=BE=E6=A0=91?= =?UTF-8?q?=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC=20Swift=20?= =?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/0513.找树左下角的值.md | 68 ++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 99f42d34..84ed3932 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -433,6 +433,74 @@ var findBottomLeftValue = function(root) { }; ``` +## Swift + +递归版本: + +```swift +var maxLen = -1 +var maxLeftValue = 0 +func findBottomLeftValue_2(_ root: TreeNode?) -> Int { + traversal(root, 0) + return maxLeftValue +} + +func traversal(_ root: TreeNode?, _ deep: Int) { + guard let root = root else { + return + } + + if root.left == nil && root.right == nil { + if deep > maxLen { + maxLen = deep + maxLeftValue = root.val + } + return + } + + if root.left != nil { + traversal(root.left, deep + 1) + } + + if root.right != nil { + traversal(root.right, deep + 1) + } + return +} +``` +层序遍历: + +```swift +func findBottomLeftValue(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + + var queue = [root] + var result = 0 + + while !queue.isEmpty { + let size = queue.count + for i in 0..