本题跟102很像,就是将二叉树的偶数层逆序输出
我是直接将上一题的结果的偶数层reverse一下
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.res = []
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
def addLevel(tree: TreeNode, level: int):
if tree is None:
return
if len(self.res) < level:
self.res.append([tree.val])
else:
self.res[level - 1].append(tree.val)
addLevel(tree.left, level + 1)
addLevel(tree.right, level + 1)
addLevel(root, 1)
for i in range(len(self.res)):
if i % 2 == 1:
self.res[i].reverse()
return self.res
但是,我对python的一些操作不是特别熟悉,其实也可以在执行的过程中就处理好
补充一点python的List知识点:
① list.insert(index, obj)
index – 对象obj需要插入的索引值
obj – 要插入列表中的对象
该方法没有返回值,但会在列表指定位置插入指定对象。
#!/usr/bin/python3
L1 = ['Google', 'Runoob', 'Taobao']
L1.insert(1, 'Baidu')
print ('列表插入元素后为 : ', L1)
输出结果为:列表插入元素后为 : [‘Google’, ‘Baidu’, ‘Runoob’, ‘Taobao’]
② list.append(object) 向列表中添加一个对象object
music_media = ['compact disc', '8-track tape', 'long playing record']
new_media = ['DVD Audio disc', 'Super Audio CD']
music_media.append(new_media)
print music_media
>>>['compact disc', '8-track tape', 'long playing record', ['DVD Audio disc', 'Super Audio CD']]
③ list.extend(sequence) 把一个序列 sequence 的内容添加到列表中
extend() 函数用于在列表末尾一次性追加另一个序列中的多个值
(用新列表扩展原来的列表)
music_media = ['compact disc', '8-track tape', 'long playing record']
new_media = ['DVD Audio disc', 'Super Audio CD']
music_media.extend(new_media)
print music_media
>>>['compact disc', '8-track tape', 'long playing record', 'DVD Audio disc', 'Super Audio CD']