103. 二叉树的锯齿形层次遍历
# 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]]
"""
if not root:
return []
level_queue = []
ans = []
level_queue.append(root)
while level_queue:
num = len(level_queue)
temp = []
while num > 0:
cur = level_queue.pop(0)
temp.append(cur.val)
if cur.left:
level_queue.append(cur.left)
if cur.right:
level_queue.append(cur.right)
num -= 1
ans.append(temp)
for i in range(ans):
if i % 2 != 0:
ans[i] = ans[i][::-1]
return ans