添加 513. 找树左下角的值 Swift 版本

This commit is contained in:
YDLIN
2022-01-22 11:38:28 +08:00
parent 2ec4867125
commit 26c7fd202a

View File

@ -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..<size {
let firstNode = queue.removeFirst()
if i == 0 {
result = firstNode.val
}
if let leftNode = firstNode.left {
queue.append(leftNode)
}
if let rightNode = firstNode.right {
queue.append(rightNode)
}
}
}
return result
}
```
-----------------------