给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
解题思路
python列表可以很简单用reverse,remove的方法来实现双向队列,所以很简单
AC代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:if not root:return []queue = [root]flag = Trueres = []while queue:templist = []if flag:length = len(queue)for _ in range(length):temp = queue[0]templist.append(temp.val)if temp.left: queue.append(temp.left)if temp.right: queue.append(temp.right)queue.remove(temp)flag = not flagelse:length = len(queue)for i in range(length - 1, -1, -1):temp = queue[i]templist.append(temp.val)if temp.right: queue.append(temp.right) if temp.left: queue.append(temp.left)queue.remove(temp)queue.reverse()flag = not flagres.append(templist)return res