您的位置:首页 > 编程语言 > Python开发

103. Binary Tree Zigzag Level Order Traversal【M】

2017-03-29 10:09 316 查看
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]
]


Subscribe to see which companies asked this question.

这道题的关键在于,怎么判断每一层,以及,怎么zigzag地遍历

一个是,每一层分别记录,然后根据层数,把结果置反

另一个是,对每一层判断,分奇数偶数,然后,把结果插入的时候,一个是不断插在队伍的最前面,另一个是不断插在队伍的最后

# 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):
if not root:
return []

s = [root]
s1 = []
level = 1
res = []
while 1:
temp = []
for i in s:
if level % 2 == 1:
temp += i.val,
else:
temp = [i.val] + temp

if i.left:
s1 += i.left,
if i.right:
s1 += i.right,
level += 1
#print temp
res += temp,
if s1 == []:
break
s = s1[:]
s1 = []
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息