给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
Python 解答:
# 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: TreeNode) -> List[List[int]]:
res = []
if not root:
return res
level = [root.val]
temp = [root]
flag = True
while temp:
if flag:
res.append(level)
else:
res.append(level[::-1])
level = []
node = []
for i in range(len(temp)):
if temp[i].left:
node.append(temp[i].left)
level.append(temp[i].left.val)
if temp[i].right:
node.append(temp[i].right)
level.append(temp[i].right.val)
temp = node
flag = not flag
return res
留言