标签:-o info append node self time line mission sub
https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
层序遍历,然后把结果反一下返回值就可以了
res=[] if not root: return res queue=collections.deque() queue.append(root) while queue: level=[] for i in range(len(queue)): node=queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(level) return res.reverse()
最后一步有问题,reverse()函数没有返回值,应该使用 res[::-1]
Runtime: 44 ms, faster than 49.24% of Python3 online submissions for Binary Tree Level Order Traversal II.
class Solution: def __init__(self): self.traverse=[] def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] level = [root] self.traverse.append([node.val for node in level]) self.traverse_helper(level) return self.traverse[::-1] def traverse_helper(self,level): if not level: return queue = [] for node in level: if node.left: queue.append(node.left) if node.right: queue.append(node.right) if not queue: return self.traverse.append([node.val for node in queue]) self.print_traverse(queue) self.traverse_helper(queue) def print_traverse(self,level): for node in level: print(node.val)
107. Binary Tree Level Order Traversal II
标签:-o info append node self time line mission sub
原文地址:https://www.cnblogs.com/captain-dl/p/10332222.html