给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回锯齿形层次遍历如下:
[ [3], [20,9], [15,7] ]
思路:
还是二叉树的层序遍历,只需要加一个变量lor(left or right)来判断当前层是从左端开始,还是从右端开始。
# 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]]
"""
queue = [root]
lor = 0 # 0 for left and 1 for right
res = list()
if not root:
return []
while(queue):
next_queue = list()
layer = list()
for node in queue:
if node.left:
next_queue.append(node.left)
if node.right:
next_queue.append(node.right)
layer.append(node.val)
if not lor: # left
res.append(layer)
else:
res.append(layer[::-1])
lor = 1 - lor
queue = next_queue
return res