给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回锯齿形层次遍历如下:
[ [3], [20,9], [15,7] ]
思路:这里要理解锯齿型,就是从根节点开始,从左往右遍历,下一层就从右往左,跟102层次遍历的题很像,只不过要加一个flag控制往左或往右遍历,也是BFS。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
res = []
nodeList = [root]
flag = 1
while nodeList:
resTemp = []
length = len(nodeList)
for i in range(length):
temp = nodeList.pop(0)
resTemp.append(temp.val)
if temp.left:
nodeList.append(temp.left)
if temp.right:
nodeList.append(temp.right)
if flag == -1:
res.append(resTemp[::-1])
res.append(resTemp)
flag *= -1
return res