LintCode:二叉树的锯齿形层次遍历
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: A list of list of integer include
the zig zag level order traversal of its nodes' values
"""
def zigzagLevelOrder(self, root):
# write your code here
if root == None:
return []
L1 = [root]
ans = [[root.val]]
flag = 1
while L1:
L2 = []
L3 = []
while L1:
node = L1[0]
if node.left != None:
L2.append(node.left)
if node.right != None:
L2.append(node.right)
L1.remove(node)
if L2:
if flag % 2 == 1:
L3 = [node.val for node in L2][::-1]
else:
L3 = [node.val for node in L2]
flag += 1
ans.append(L3)
L1 = L2
return ans