@@ -581,7 +581,72 @@ var binaryTreePaths = function(root) {
581
581
};
582
582
```
583
583
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
+ ```
584
618
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
+ ```
585
650
586
651
-----------------------
587
652
<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
0 commit comments