二叉树的迭代遍历:补充Swift实现

# Conflicts:
#	problems/二叉树的迭代遍历.md
This commit is contained in:
bqlin
2021-12-21 11:55:45 +08:00
committed by Bq
parent 28cff716ac
commit a9ae0f5d03

View File

@@ -390,7 +390,7 @@ func inorderTraversal(root *TreeNode) []int {
} }
``` ```
javaScript javaScript
```js ```js
@@ -454,7 +454,7 @@ var postorderTraversal = function(root, res = []) {
}; };
``` ```
TypeScript: TypeScript
```typescript ```typescript
// 前序遍历(迭代法) // 前序遍历(迭代法)
@@ -509,77 +509,63 @@ function postorderTraversal(root: TreeNode | null): number[] {
}; };
``` ```
Swift: Swift
> 迭代法前序遍历
```swift ```swift
//
func preorderTraversal(_ root: TreeNode?) -> [Int] { func preorderTraversal(_ root: TreeNode?) -> [Int] {
var res = [Int]() var result = [Int]()
if root == nil { guard let root = root else { return result }
return res var stack = [root]
}
var stack = [TreeNode]()
stack.append(root!)
while !stack.isEmpty { while !stack.isEmpty {
let node = stack.popLast()! let current = stack.removeLast()
res.append(node.val) //
if node.right != nil { if let node = current.right { //
stack.append(node.right!) stack.append(node)
} }
if node.left != nil { if let node = current.left { //
stack.append(node.left!) stack.append(node)
} }
result.append(current.val) //
} }
return res return result
} }
```
> 迭代法中序遍历 //
```swift
func inorderTraversal(_ root: TreeNode?) -> [Int] {
var res = [Int]()
if root == nil {
return res
}
var stack = [TreeNode]()
var cur: TreeNode? = root
while cur != nil || !stack.isEmpty {
if cur != nil {
stack.append(cur!)
cur = cur!.left
} else {
cur = stack.popLast()
res.append(cur!.val)
cur = cur!.right
}
}
return res
}
```
> 迭代法后序遍历
```swift
func postorderTraversal(_ root: TreeNode?) -> [Int] { func postorderTraversal(_ root: TreeNode?) -> [Int] {
var res = [Int]() var result = [Int]()
if root == nil { guard let root = root else { return result }
return res var stack = [root]
}
var stack = [TreeNode]()
stack.append(root!)
// res -> ->
while !stack.isEmpty { while !stack.isEmpty {
let node = stack.popLast()! let current = stack.removeLast()
res.append(node.val) //
if node.left != nil { if let node = current.left { //
stack.append(node.left!) stack.append(node)
} }
if node.right != nil { if let node = current.right { //
stack.append(node.right!) stack.append(node)
}
result.append(current.val) //
}
return result.reversed()
}
//
func inorderTraversal(_ root: TreeNode?) -> [Int] {
var result = [Int]()
var stack = [TreeNode]()
var current: TreeNode! = root
while current != nil || !stack.isEmpty {
if current != nil { // 访
stack.append(current)
current = current.left //
} else {
current = stack.removeLast()
result.append(current.val) //
current = current.right //
} }
} }
// res return result
res.reverse()
return res
} }
``` ```