给你二叉树的根节点 root
,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例:
输入:root = [3,9,20,null,null,15,7] 输出:[[3],[20,9],[15,7]]
解析:
只需要先层序遍历,然后将奇数层翻转一下即可。不懂层序遍历的可以看这一篇:https://blog.csdn.net/qq_43593534/article/details/123800081?spm=1001.2014.3001.5502
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root: return []
def levelOrder(root): # 层序遍历
res = []
if root :
queue = [root]
else:
return res
while len(queue):
n = len(queue)
r = []
for _ in range(n):
node = queue.pop(0)
r.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(r)
return res
def reverse(level_order): # 翻转,因为LeetCode里reverse()函数不可用,只能自己实现一下了。
reverse = 0
res = []
for level in level_order:
if not reverse:
res.append(level)
reverse = 1
else:
res.append(level[::-1])
reverse = 0
return res
res = reverse(levelOrder(root))
return res