funcpreorderTraversal(root *TreeNode)[]int{
res :=make([]int,0)dfsPreorderRecursively(root,&res)return res
}funcdfsPreorderRecursively(root *TreeNode, res *[]int){if root !=nil{*res =append(*res, root.Val)dfsPreorderRecursively(root.Left, res)dfsPreorderRecursively(root.Right, res)}}
funcpreorderTraversal(root *TreeNode)[]int{
res :=make([]int,0)// 栈
st :=make([]*TreeNode,0)// 当前遍历节点
cur := root
for cur !=nil||len(st)>0{for cur !=nil{// 根
res =append(res, cur.Val)// 左子树
st =append(st, cur)
cur = cur.Left
}// 右子树
cur = st[len(st)-1]
st = st[0:len(st)-1]
cur = cur.Right
}return res
}
funcinorderTraversal(root *TreeNode)[]int{
res :=make([]int,0)dfsInorderRecursively(root,&res)return res
}funcdfsInorderRecursively(root *TreeNode, res *[]int){if root !=nil{dfsInorderRecursively(root.Left, res)*res =append(*res, root.Val)dfsInorderRecursively(root.Right, res)}}
funcinorderTraversal(root *TreeNode)[]int{
res :=make([]int,0)// 栈
st :=make([]*TreeNode,0)// 当前节点
cur := root
for cur !=nil||len(st)!=0{// 左子树for cur !=nil{
st =append(st, cur)
cur = cur.Left
}// 根
cur = st[len(st)-1]
st = st[0:len(st)-1]
res =append(res, cur.Val)// 右子树
cur = cur.Right
}return res
}
funcpostorderTraversalWithRecursion(root *TreeNode)[]int{
res :=make([]int,0)dfsInorderRecursively(root,&res)return res
}funcdfsPostorderRecursively(root *TreeNode, res *[]int){if root !=nil{dfsInorderRecursively(root.Left, res)dfsInorderRecursively(root.Right, res)*res =append(*res, root.Val)}}
funcpostorderTraversal(root *TreeNode)[]int{
res :=make([]int,0)// stack
st :=make([]*TreeNode,0)// current node
cur := root
// previous nodevar prev *TreeNode
for cur !=nil||len(st)>0{// left treefor cur !=nil{
st =append(st, cur)
cur = cur.Left
}
cur = st[len(st)-1]if cur.Right !=nil&& cur.Right != prev {// right tree
cur = cur.Right
}else{// root
res =append(res, cur.Val)
st = st[:len(st)-1]
prev = cur
cur =nil}}return res
}
type Codec struct{}funcConstructor() Codec {return Codec{}}// Serializes a tree to a single string.func(this *Codec)serialize(root *TreeNode)string{var f func(*TreeNode)string
f =func(node *TreeNode)string{var sb strings.Builder
// 递归出口if node ==nil{return"null"}// root
rootStr := strconv.Itoa(node.Val)// left
leftStr :=f(node.Left)// right
rightStr :=f(node.Right)
sb.WriteString(rootStr)
sb.WriteByte(',')
sb.WriteString(leftStr)
sb.WriteByte(',')
sb.WriteString(rightStr)return sb.String()}returnf(root)}// Deserializes your encoded data to tree.func(this *Codec)deserialize(data string)*TreeNode {
strs := strings.Split(data,",")returndfs(&strs)}funcdfs(strs *[]string)*TreeNode {iflen(*strs)==0{returnnil}// node val
str :=(*strs)[0]*strs =(*strs)[1:]if str =="null"{returnnil}
val,_:= strconv.Atoi(str)// root node
root :=&TreeNode{Val: val}// left tree
root.Left =dfs(strs)// right tree
root.Right =dfs(strs)return root
}