Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range?
[0, 2000] . -100 <= Node.val <= 100
题目要求以水平Z字型顺序遍历整棵二叉树,也就是以行为单位,一行从左到右,下一行就从右到左,这样交替进行遍历二叉树。
如果对水平遍历二叉树算法比较熟悉,这题就比较简单。思路差不多,利用BFS算法以行为单位进行遍历。定义一个队列queue,每次把整行节点放入队列中,每一次循环把当前队列中的所有节点(即整行的节点)挨个取出,把值放入一个临时数组中,再把取出节点的左右子节点(如果存在的话)放入队列中。由于要求要Z字型,每隔一行需要把临时数组反转。最后把临时数组的所有数加入到答案数组中。
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
res = []
l2r = True
q = deque([root])
while q:
n = len(q)
level = []
for i in range(n):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if l2r:
l2r = False
else:
l2r = True
level.reverse()
res.append(level)
return res
|