golang 前中后序遍历(非递归)
作者:互联网
先写后续,后续复杂点
func postorderTraversal(root *TreeNode) []int {
res := make([]int,0)
//记录访问过的节点
hash:=make(map[*TreeNode]bool)
stack:=make([]*TreeNode,0)
rt:=root
for len(stack)!=0||rt!=nil{
for rt!=nil{
stack = append(stack,rt)
rt = rt.Left
}
//取出栈顶元素
tmp:=stack[len(stack)-1]
if tmp!=nil&&hash[tmp]{
//用过则加入结果,去除栈顶元素
stack = stack[:len(stack)-1]
res = append(res,tmp.Val)
}else{
//没用过,记录下,向右
hash[tmp] = true
rt = tmp.Right
}
}
return res
}
前序遍历
func preorderTraversal(root *TreeNode) []int { res:=make([]int,0) rt:=root stack:=make([]*TreeNode,0) for len(stack)!=0||rt!=nil{ //左边有则一直向左子树并且记录数据 for rt!=nil{ res = append(res,rt.Val) stack = append(stack,rt) rt = rt.Left } //去除栈顶,向右 tmp:=stack[len(stack)-1] stack = stack[:len(stack)-1] rt = tmp.Right } return res }
中序遍历,和前序一样,只是后面再记录数据
func inorderTraversal(root *TreeNode) []int { res:=make([]int,0) stack:=make([]*TreeNode,0) rt:=root for len(stack)!=0||rt!=nil{ for rt!=nil{ stack = append(stack,rt) rt = rt.Left } tmp:=stack[len(stack)-1] stack = stack[:len(stack)-1] //记录数据放在这里 res = append(res,tmp.Val) rt = tmp.Right } return res }
标签:rt,tmp,遍历,前中,res,make,len,golang,stack 来源: https://www.cnblogs.com/9527s/p/14261127.html