二叉树的迭代遍历:补充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
@ -454,7 +454,7 @@ var postorderTraversal = function(root, res = []) {
};
```
TypeScript:
TypeScript
```typescript
// 前序遍历(迭代法)
@ -509,77 +509,63 @@ function postorderTraversal(root: TreeNode | null): number[] {
};
```
Swift:
Swift
> 迭代法前序遍历
```swift
// 前序遍历迭代法
func preorderTraversal(_ root: TreeNode?) -> [Int] {
var res = [Int]()
if root == nil {
return res
}
var stack = [TreeNode]()
stack.append(root!)
var result = [Int]()
guard let root = root else { return result }
var stack = [root]
while !stack.isEmpty {
let node = stack.popLast()!
res.append(node.val)
if node.right != nil {
stack.append(node.right!)
let current = stack.removeLast()
// 先右后左,这样出栈的时候才是左右顺序
if let node = current.right { // 右
stack.append(node)
}
if node.left != nil {
stack.append(node.left!)
if let node = current.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] {
var res = [Int]()
if root == nil {
return res
}
var stack = [TreeNode]()
stack.append(root!)
// res 存储 中 -> 右 -> 左
var result = [Int]()
guard let root = root else { return result }
var stack = [root]
while !stack.isEmpty {
let node = stack.popLast()!
res.append(node.val)
if node.left != nil {
stack.append(node.left!)
let current = stack.removeLast()
// 与前序相反,即中右左,最后结果还需反转才是后序
if let node = current.left { // 左
stack.append(node)
}
if node.right != nil {
stack.append(node.right!)
if let node = current.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 翻转
res.reverse()
return res
return result
}
```