# 二叉树遍历

<!--more-->

## 算法思想

(图片来自知乎)

### 后序遍历

``````type TreeNode struct {
Val   int
Left  *TreeNode
Right *TreeNode
}``````

## DFS实现

#### 递归生成二叉树

``````package main

import "fmt"

type TreeNode struct {
Val   int
Left  *TreeNode
Right *TreeNode
}

func main() {
root := &TreeNode{}
dfs(root, 1)
fmt.Println(root.Left)

}

func dfs(p *TreeNode, depth int) {
if depth < 3 {
left := &TreeNode{Val: 2 * depth}
right := &TreeNode{Val: 4 * depth}
p.Left = left
p.Right = right
dfs(p.Left, depth+1)
dfs(p.Right, depth+1)
}
}``````

``````func dfsbr(p *TreeNode, res *[]int) {
if p != nil {
*res = append(*res, p.Val)
dfsbr(p.Left, res)
dfsbr(p.Right, res)
}
}``````

``````\$ go run main.go
[0 2 4 8 4 4 8]``````

### 中序遍历

``````func dfsbr(p *TreeNode, res *[]int) {
if p != nil {
dfsbr(p.Left, res)
*res = append(*res, p.Val)
dfsbr(p.Right, res)
}
}``````

### 后序遍历

``````func dfsbr(p *TreeNode, res *[]int) {
if p != nil {
dfsbr(p.Left, res)
dfsbr(p.Right, res)
*res = append(*res, p.Val)
}
}``````

## BFS实现

### 层序遍历

``````func bfs(p *TreeNode) []int {
res := make([]int, 0)
if p == nil {
return res
}
queue := []*TreeNode{p}
for len(queue) > 0 {
length := len(queue)
for length > 0 {
length--
if queue[0].Left != nil {
queue = append(queue, queue[0].Left)
}
if queue[0].Right != nil {
queue = append(queue, queue[0].Right)
}
res = append(res, queue[0].Val)
queue = queue[1:]
}
}
return res
}``````

``````\$ go run main.go
[0 2 4 4 8 4 8]``````

### 先序遍历

``````/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func preorderTraversal(root *TreeNode) []int {
result := make([]int, 0)

if root == nil {
return result
}

queue := make([]*TreeNode, 0)

for len(queue) > 0 || root != nil {
for root != nil {
result = append(result, root.Val)
queue = append(queue, root)
root = root.Left
}
root = queue[len(queue) - 1].Right
queue = queue[:len(queue) - 1]
}
return result
}``````

### 中序遍历

``````/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func inorderTraversal(root *TreeNode) []int {
result := make([]int, 0)

if root == nil {
return result
}

queue := make([]*TreeNode, 0)

for len(queue) > 0 || root != nil {
for root != nil {
queue = append(queue, root)
root = root.Left
}

node := queue[len(queue) - 1]
queue = queue[:len(queue) - 1]
result = append(result, node.Val)
root = node.Right
}
return result
}``````

### 后序遍历

``````func postorderTraversal(root *TreeNode) []int {
result := make([]int, 0)

if root == nil {
return result
}

queue := make([]*TreeNode, 0)
var lastVisited *TreeNode

for len(queue) > 0 || root != nil{
for root != nil {
queue = append(queue, root)
root = root.Left
}
n := queue[len(queue) - 1]
if n.Right == nil || n.Right == lastVisited {
result = append(result, n.Val)
queue = queue[:len(queue) - 1]
lastVisited = n
} else {
root = n.Right
}
}

return result
}``````