package main

import "fmt"

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


func main() {
root := TreeNode{Val: 1}
rootfirst := TreeNode{Val: 2}
rootSecond := TreeNode{Val: 3}
root.Left = &rootfirst
root.Right = &rootSecond
fmt.Println(levelTraversal(&root))
fmt.Println(inorderTraversal(&root))
fmt.Println(inorderTraversal1(&root))
fmt.Println(preorderTraversal(&root))
fmt.Println(preorderTraversal1(&root))
fmt.Println(postorderTraversal(&root))
}

//中序--递归
func inorderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
left := inorderTraversal(root.Left)
right := inorderTraversal(root.Right)
res := left
res = append(res,root.Val)
res = append(res,right...)
return res
}
//中序--迭代
func inorderTraversal1(root *TreeNode) []int {
if root==nil {
return nil
}
stack := make([]*TreeNode,0)
res := make([]int,0)
for len(stack)>0 || root!=nil {
for root!= nil {
stack = append(stack,root)
root = root.Left
}
last := len(stack)-1
res = append(res,stack[last].Val)
root = stack[last].Right
stack = stack[:last]
}
return res
}


//先序--递归
func preorderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
left := preorderTraversal(root.Left)
right := preorderTraversal(root.Right)
var res []int
res = append(res,root.Val)
res = append(res,left...)
res = append(res,right...)
return res
}
//先序--迭代
func preorderTraversal1(root *TreeNode) []int {
if root==nil {
return nil
}
stack := make([]*TreeNode,0)
res := make([]int,0)
for len(stack)>0 || root!=nil {
for root!= nil {
res = append(res,root.Val)
stack = append(stack,root.Right)
root = root.Left
}
last := len(stack)-1
root = stack[last]
stack = stack[:last]
}
return res
}
//后序--递归
func postorderTraversal(root *TreeNode) []int {
if root == nil {
return nil
}
left := postorderTraversal(root.Left)
right := postorderTraversal(root.Right)
var res []int
res = append(res,left...)
res = append(res,right...)
res = append(res,root.Val)
return res
}


//层次
func levelTraversal( root *TreeNode ) [][]int {
if root == nil{
return [][]int{}
}
var result [][]int
queue := []*TreeNode{root}
for len(queue)>0{
currentQueue := queue[:]
queue = make([]*TreeNode, 0)
level := make([]int,0)
for _,value := range currentQueue {
level = append(level, value.Val)
if value.Left != nil {
queue = append(queue, value.Left)
}
if value.Right != nil {
queue = append(queue, value.Right)
}
}
result = append(result, level)
}
return result
}