1.题目描述
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
2.思路
- 按层次遍历依次从左到右遍历每个根节点的左右节点,至于其中偶数层的逆序,借鉴其他博客的方法,用一个随层数奇偶变化的 数字1和-1来做标记。
在返回子列表时,先对标记做判断,如果为-1时,则将列表逆序输出即可
3.代码
# 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]]
"""
res = []
if not root:
return res
node_list = [root]
# 奇偶标记数字
lag = 1
while node_list:
templist = []
for i in range(len(node_list)):
temp = node_list.pop(0)
templist.append(temp.val)
if temp.left:
node_list.append(temp.left)
if temp.right:
node_list.append(temp.right)
if lag == -1:
# 为-1则说明为偶数层,逆序输出
templist[:] = templist[::-1]
res.append(templist)
lag *= -1
return res