# Swift 刷题 二叉树的前中后三种遍历

#### 二叉树

``````//Definition for a binary tree node.
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}

class Solution {
var traversals = Array<Int>()
func treeTraversal(_ root: TreeNode?) -> [Int] {
guard root != nil else {
return []
}
return traversals
}
}

##### 递归

1. 确定递归的参数以及返回值
2. 确定递归的终止条件 递归算法一定有终止条件，避免死循环。
3. 确定单次递归的逻辑
###### 前序遍历
``````    /// 前序遍历
func preorder(_ node: TreeNode?) {
guard node != nil else {
return
}
traversals.append(node!.val)
preorder(node?.left)
preorder(node?.right)
}

###### 中序遍历
``````    /// 中序遍历
func inorder(_ node: TreeNode?) {
guard node != nil else {
return
}
preorder(node?.left)
traversals.append(node!.val)
preorder(node?.right)
}

###### 后序遍历
``````    /// 后续遍历
func postorder(_ node: TreeNode?) {
guard node != nil else {
return
}
preorder(node?.left)
preorder(node?.right)
traversals.append(node!.val)

}

##### 迭代

###### 前序遍历
``````func preorderIteration(_ root: TreeNode?) {
var st:[TreeNode?] = [root]
while !st.isEmpty {
let node = st.removeFirst()
if node != nil {
traversals.append(node!.val)
}else {
continue
}
st.insert(node?.right, at: 0)
st.insert(node?.left, at: 0)
}
}

###### 中序遍历
``````func inorderIteration(_ root: TreeNode?) {
var st:[TreeNode?] = []
var cur:TreeNode? = root
while cur != nil || !st.isEmpty {
if cur != nil {
st.insert(cur, at: 0)
cur = cur?.left
}else {
cur = st.removeFirst()
traversals.append(cur!.val)
cur = cur?.right
}
}
}

###### 后序遍历

``````func postorderIteration(_ root: TreeNode?) {
var st:[TreeNode?] = [root]
while !st.isEmpty {
let node = st.removeFirst()
if node != nil {
print(node!.val)
traversals.append(node!.val)
}else {
continue
}
st.insert(node?.left, at: 0)
st.insert(node?.right, at: 0)
}
traversals = traversals.reversed()
}

##### 颜色标记法

``````    func tuple(_ root: TreeNode?) -> [Int] {
//前序 中左右 按照右左中
//中序 左中右 按照右中左
//后序 左右中 按照中右左
var result = [Int]()
var statck = [(0, root)]
while !statck.isEmpty {
let (isVisted, node) = statck.removeLast()
if node == nil {
continue
}
if isVisted == 0 {
//                ///前序遍历
//                statck.append((0, node?.right))
//                statck.append((0, node?.left))
//                statck.append((1, node))
//                ///中序遍历
//                statck.append((0, node?.right))
//                statck.append((1, node))
//                statck.append((0, node?.left))
///后序遍历
statck.append((1, node))
statck.append((0, node?.right))
statck.append((0, node?.left))
} else {
result.append(node!.val)
}
}
return result
}