二叉树的迭代遍历:补充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
} }
``` ```