[LeetCode By Python]107. Binary Tree Level Order Traversal II
1521 ワード
タイトル:
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example: Given binary tree
return its bottom-up level order traversal as:
daコード+デバッグ:
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example: Given binary tree
[3,9,20,null,null,15,7]
, 3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
daコード+デバッグ:
# 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]]
"""
results = []
if root == None:
return results
curr_level = [root]
while curr_level:
curr_result = []
next_level = []
for i in curr_level:
curr_result.append(i.val)
if i.left:
next_level.append(i.left)
if i.right:
next_level.append(i.right)
results.append(curr_result)
curr_level = next_level
results.reverse()
return results
if __name__ == '__main__':
l1_1 = TreeNode(1)
l1_2 = TreeNode(2)
l1_3 = TreeNode(3)
l1_1.left = l1_2
l1_1.right = l1_3
l3 = Solution().levelOrderBottom(l1_1)
print l3