package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
/**
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
*/
func main() {
root := &TreeNode{
Val: 1,
Left: &TreeNode{
Val: 2,
Left: &TreeNode{
Val: 4,
Left: &TreeNode{
Val: 8,
Left: nil,
Right: nil,
},
Right: &TreeNode{
Val: 9,
Left: nil,
Right: nil,
},
},
Right: &TreeNode{
Val: 5,
Left: &TreeNode{
Val: 10,
Left: nil,
Right: nil,
},
Right: &TreeNode{
Val: 11,
Left: nil,
Right: nil,
},
},
},
Right: &TreeNode{
Val: 3,
Left: &TreeNode{
Val: 6,
Left: &TreeNode{
Val: 12,
Left: nil,
Right: nil,
},
Right: &TreeNode{
Val: 13,
Left: nil,
Right: nil,
},
},
Right: &TreeNode{
Val: 7,
Left: &TreeNode{
Val: 14,
Left: nil,
Right: nil,
},
Right: &TreeNode{
Val: 15,
Left: nil,
Right: nil,
},
},
},
}
res := preOrder(root)
fmt.Println("前序遍历", res) // 前序遍历 [1 2 4 5 3 6]
res = MidOrder(root)
fmt.Println("中序遍历", res) // 中序遍历 [4 2 5 1 6 3]
res = PostOrder(root)
fmt.Println("后序遍历", res) // 后序遍历 [4 5 2 6 3 1]
levelOr := levelOrder(root)
fmt.Println("层次遍历", levelOr) // 层次遍历 [[1] [2 3] [4 5 6]]
}
// 前序遍历
func preOrder(root *TreeNode) (res []int) {
if root == nil {
return
}
res = append(res, root.Val)
res = append(res, preOrder(root.Left)...)
res = append(res, preOrder(root.Right)...)
return res
}
// 中序遍历
func MidOrder(root *TreeNode) (res []int) {
if root == nil {
return
}
res = append(res, MidOrder(root.Left)...)
res = append(res, root.Val)
res = append(res, MidOrder(root.Right)...)
return res
}
// 后序遍历
func PostOrder(root *TreeNode) (res []int) {
if root == nil {
return
}
res = append(res, PostOrder(root.Left)...)
res = append(res, PostOrder(root.Right)...)
res = append(res, root.Val)
return res
}
// 层次遍历
func levelOrder(root *TreeNode) [][]int {
// 定义返回二维数组
ret := [][]int{}
if root == nil {
return ret
}
// 记录每一层的节点
temp := []int{}
// 根节点入队
queue := []*TreeNode{root}
// 队列不为空
for len(queue) > 0 {
// 后续有入队操作,保存当前len(queue)
length := len(queue)
// 更新
temp = []int{}
for i := 0; i < length; i++ {
// 记录当前节点
node := queue[0]
// 出队
queue = queue[1:]
// 如果有左孩子,入队
if node.Left != nil {
queue = append(queue, node.Left)
}
// 如果有右孩子,入队
if node.Right != nil {
queue = append(queue, node.Right)
}
// 记录当前节点Val
temp = append(temp, node.Val)
}
ret = append(ret, temp)
}
return ret
}