leetcode 103. 二叉树的锯齿形层次遍历

题目链接:leetcode

思路:广度优先遍历,加一个标志flag判断是否转换位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
flag = 1
if not root:return []
q = deque()
q.append(root)
res = []
while q:
n = len(q)
tmp = []
for i in range(n):
node = q.popleft()
tmp.append(node.val)
if node.left:q.append(node.left)
if node.right:q.append(node.right)
if flag==1:
res.append(tmp)
flag = 0
else:
res.append(tmp[::-1])
flag = 1
return res