GO题解 | #二叉树的之字形层序遍历#
来自
【GO题解】
577 浏览
0 回复
2021-04-23
二叉树的之字形层序遍历
http://www.nowcoder.com/practice/47e1687126fa461e8a3aff8632aa5559
go解题答案
- 时间复杂度O(n)
- 思路概括:双队列+逆序
- 思路核心:
1、 普通层序遍历+单数层节点逆序func zigzagLevelOrder( root *TreeNode ) [][]int {
// write code here
if root==nil {
return nil
}
res:= [][]int{}
queue:=[]*TreeNode{root} //初始化队列
for i:=0;len(queue)>0;i++{
temp:=[]int{} //本层数组
levelNodes:=[]*TreeNode{} //下层节点
for j:=0;j<len(queue);j++{ //处理队列节点
cur:=queue[j]
temp=append(temp,cur.Val) //直接加入本层数组
if cur.Left != nil { // 下层节点入队列
levelNodes = append(levelNodes, cur.Left)
}
if cur.Right != nil {
levelNodes = append(levelNodes, cur.Right)
}
}
if i%2 == 1 { //从0开始,单数层交换
for i, n := 0, len(temp); i < n/2; i++ {
temp[i], temp[n-1-i] = temp[n-1-i], temp[i]
}
}
res= append(res,temp) //本层节点push到返回值
queue=levelNodes //队列重新赋值
}
return res
}
如果有帮助请点个赞哦, 更多文章请看我的博客
题主背景
- 从业8年——超级内卷500Q技术经理——目前专注go和微服务架构