Question
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,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.
Show Tags
Show Similar Problems
Analysis
This problem can be sees as an extension of the level order traversal. One flag variable is used to decide whether the current list will be reversed.
Solution
# 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 root==None:
return []
queue, lst, cur, res = [root], [], [], []
lastnum, curnum = 1, 0
flag = 0 # if false, print all nodes in current level in the reverse order
while queue!=[]:
while lastnum>0:
temp = queue[0]
queue = queue[1:]
lastnum -= 1
lst.append(temp.val)
if temp.left!=None:
queue.append(temp.left)
curnum += 1
if temp.right!=None:
queue.append(temp.right)
curnum += 1
if flag%2==1:
newlst = []
for elem in lst:
newlst = [elem] + newlst
else:
newlst = lst
res.append(newlst)
lastnum = curnum
curnum = 0
lst = []
flag += 1
return res
Error Path
- forget to update lst to be [] after the inner while. keep an eye on it !
- when reversing lst, write newlst = newlst +[elem] instead of newlst = [elem] + newlst.
Take home message
In python, if flag=1, and flag = ~flag. The flag will not be change to be 1 as expected, but changed to be -1.
8549




被折叠的 条评论
为什么被折叠?



