- 二叉树的锯齿形层序遍历
给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
树中节点数目在范围 [0, 2000] 内
-100 <= Node.val <= 100
# 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]
curLevel = 1
curSize = 1
nextSize = 0
res = []
while queue:
level = []
if curLevel % 2 == 1:
for _ in range(curSize):
t = queue.pop(0)
level.append(t.val)
if t.left:
queue.append(t.left)
nextSize += 1
if t.right:
queue.append(t.right)
nextSize+=1
if curLevel % 2 == 0:
for _ in range(curSize):
t = queue.pop(-1)
level.append(t.val)
if t.right:
queue.insert(0,t.right)
nextSize+=1
if t.left:
queue.insert(0,t.left)
nextSize += 1
curLevel += 1
curSize = nextSize
nextSize = 0
res.append(level)
return res
标签:right,val,Python,层序,queue,二叉树,nextSize,root,left
From: https://www.cnblogs.com/DCFV/p/18572023