Skip to content

Commit 0e75c5d

Browse files
committed
添加 257. 二叉树的所有路径 Swift版本
1 parent f00b06e commit 0e75c5d

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

problems/0257.二叉树的所有路径.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -581,7 +581,72 @@ var binaryTreePaths = function(root) {
581581
};
582582
```
583583

584+
Swift:
585+
586+
> 递归/回溯
587+
```swift
588+
func binaryTreePaths(_ root: TreeNode?) -> [String] {
589+
var res = [String]()
590+
guard let root = root else {
591+
return res
592+
}
593+
var path = [Int]()
594+
_binaryTreePaths(root, path: &path, res: &res)
595+
return res
596+
}
597+
func _binaryTreePaths(_ root: TreeNode, path: inout [Int], res: inout [String]) {
598+
path.append(root.val)
599+
if root.left == nil && root.right == nil {
600+
var str = ""
601+
for i in 0 ..< path.count - 1 {
602+
str.append("\(path[i])->")
603+
}
604+
str.append("\(path.last!)")
605+
res.append(str)
606+
return
607+
}
608+
if let left = root.left {
609+
_binaryTreePaths(left, path: &path, res: &res)
610+
path.removeLast()
611+
}
612+
if let right = root.right {
613+
_binaryTreePaths(right, path: &path, res: &res)
614+
path.removeLast()
615+
}
616+
}
617+
```
584618
619+
> 迭代
620+
```swift
621+
func binaryTreePaths(_ root: TreeNode?) -> [String] {
622+
var res = [String]()
623+
guard let root = root else {
624+
return res
625+
}
626+
var stackNode = [TreeNode]()
627+
stackNode.append(root)
628+
629+
var stackStr = [String]()
630+
stackStr.append("\(root.val)")
631+
632+
while !stackNode.isEmpty {
633+
let node = stackNode.popLast()!
634+
let str = stackStr.popLast()!
635+
if node.left == nil && node.right == nil {
636+
res.append(str)
637+
}
638+
if let left = node.left {
639+
stackNode.append(left)
640+
stackStr.append("\(str)->\(left.val)")
641+
}
642+
if let right = node.right {
643+
stackNode.append(right)
644+
stackStr.append("\(str)->\(right.val)")
645+
}
646+
}
647+
return res
648+
}
649+
```
585650

586651
-----------------------
587652
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)