LeetCode-103、二叉树的锯齿形层次遍历-中等
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
ans = []
def recursion(nodes, label):
tmp = []
nex = []
for cur in nodes:
if label == 1:
tmp.append(cur.val)
if label == -1:
tmp.insert(0, cur.val)
if cur.left:
nex.append(cur.left)
if cur.right:
nex.append(cur.right)
ans.append(tmp)
label *= (-1)
if nex:
recursion(nex, label)
if root:
recursion([root], 1)
return ans