添加 0112.路径总和、0113.路径总和 II Swift 版本

This commit is contained in:
YDLIN
2022-01-24 11:36:06 +08:00
parent 954f291adb
commit 00728847e1

View File

@ -766,7 +766,124 @@ let pathSum = function(root, targetSum) {
}; };
``` ```
## Swift
0112.路径总和
**递归**
```swift
func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool {
guard let root = root else {
return false
}
return traversal(root, targetSum - root.val)
}
func traversal(_ cur: TreeNode?, _ count: Int) -> Bool {
if cur?.left == nil && cur?.right == nil && count == 0 {
return true
}
if cur?.left == nil && cur?.right == nil {
return false
}
if let leftNode = cur?.left {
if traversal(leftNode, count - leftNode.val) {
return true
}
}
if let rightNode = cur?.right {
if traversal(rightNode, count - rightNode.val) {
return true
}
}
return false
}
```
**迭代**
```swift
func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool {
guard let root = root else {
return false
}
var stack = Array<(TreeNode, Int)>()
stack.append((root, root.val))
while !stack.isEmpty {
let node = stack.removeLast()
if node.0.left == nil && node.0.right == nil && targetSum == node.1 {
return true
}
if let rightNode = node.0.right {
stack.append((rightNode, node.1 + rightNode.val))
}
if let leftNode = node.0.left {
stack.append((leftNode, node.1 + leftNode.val))
}
}
return false
}
```
0113.路径总和 II
**递归**
```swift
var result = [[Int]]()
var path = [Int]()
func pathSum(_ root: TreeNode?, _ targetSum: Int) -> [[Int]] {
result.removeAll()
path.removeAll()
guard let root = root else {
return result
}
path.append(root.val)
traversal(root, count: targetSum - root.val)
return result
}
func traversal(_ cur: TreeNode?, count: Int) {
var count = count
// 遇到了叶子节点且找到了和为targetSum的路径
if cur?.left == nil && cur?.right == nil && count == 0 {
result.append(path)
return
}
// 遇到叶子节点而没有找到合适的边,直接返回
if cur?.left == nil && cur?.right == nil{
return
}
if let leftNode = cur?.left {
path.append(leftNode.val)
count -= leftNode.val
traversal(leftNode, count: count)// 递归
count += leftNode.val// 回溯
path.removeLast()// 回溯
}
if let rightNode = cur?.right {
path.append(rightNode.val)
count -= rightNode.val
traversal(rightNode, count: count)// 递归
count += rightNode.val// 回溯
path.removeLast()// 回溯
}
return
}
```