题目描述:
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例:
例如:
给定二叉树 [3,9,20,null,null,15,7],3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:[
[3],
[20,9],
[15,7]
]
分析:
这是一套典型的层序遍历,不同的地方在于,偶数行的时候是从右到左遍历。
使用一个flag字段标记偶数行还是奇数行
层次遍历直接套用模板
代码:
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
queue = [[root]]
res = []
flag = 1
while queue[-1]:
cur = queue.pop()
tmp_res = []
tmp_que = []
if not cur:
break
for c in cur:
tmp_res.append(c.val)
if c.left:
tmp_que.append(c.left)
if c.right:
tmp_que.append(c.right)
if flag == 1:
res.append(tmp_res)
else:
res.append(tmp_res[::-1])
flag *= -1
queue.append(tmp_que)
return res
复杂度分析:
- 时间复杂度:O(n)
- 空间复杂度:O(n)