mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2024-11-28 06:48:53 +00:00
添加 Swift 代码实现
This commit is contained in:
parent
9116bc63ce
commit
f972620873
@ -67,3 +67,32 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift Code:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
class Solution {
|
||||||
|
|
||||||
|
func preorderTraversal(_ root: TreeNode?) -> [Int] {
|
||||||
|
var list:[Int] = []
|
||||||
|
var stack:[TreeNode] = []
|
||||||
|
|
||||||
|
guard root != nil else {
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
stack.append(root!)
|
||||||
|
while !stack.isEmpty {
|
||||||
|
let temp = stack.popLast()
|
||||||
|
if let right = temp?.right {
|
||||||
|
stack.append(right)
|
||||||
|
}
|
||||||
|
if let left = temp?.left {
|
||||||
|
stack.append(left)
|
||||||
|
}
|
||||||
|
//这里也可以放到前面
|
||||||
|
list.append((temp?.val)!)
|
||||||
|
}
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user