LeetCode解题之Binary Tree Level Order Traversal II
原题
实现树的广度优先遍历的倒序遍历。即从最底层依次向上遍历,每一层上的数据依照从左到右的顺序排列。
注意点:
- 无
样例:
输入:
3
/
9 20
/
15 7
输出:
[
[15,7],
[9,20],
[3]
]
解题思路
直接复用了 Binary Tree Level Order Traversal 的代码。仅仅是最后把序列翻转了。
AC源代码
# 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 levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
result = []
if not root:
return result
curr_level = [root]
while curr_level:
level_result = []
next_level = []
for temp in curr_level:
level_result.append(temp.val)
if temp.left:
next_level.append(temp.left)
if temp.right:
next_level.append(temp.right)
result.append(level_result)
curr_level = next_level
result.reverse()
return result
if __name__ == "__main__":
None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。