标签:turn nod ini append sel treenode bsp imp span
Given a binary tree, return the zigzag level order traversal of its nodes‘ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
# 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]] """ from collections import deque res = [] if root is None: return res is_even = False my_deque = deque() my_deque.append(root) while my_deque: size = len(my_deque) lst = [] for _ in range(size): if is_even: cur = my_deque.pop() if cur.right: my_deque.appendleft(cur.right) if cur.left: my_deque.appendleft(cur.left) else: cur = my_deque.popleft() if cur.left: my_deque.append(cur.left) if cur.right: my_deque.append(cur.right) lst.append(cur.val) res.append(lst) is_even = not is_even return res
[LC] 103. Binary Tree Zigzag Level Order Traversal
标签:turn nod ini append sel treenode bsp imp span
原文地址:https://www.cnblogs.com/xuanlu/p/11718930.html