思路:用两个列表分别保存当前层节点和下一层节点,结果.append([i.val for i in 当前层节点]),然后 当前层列表,下一层列表 = 下一层列表, [] 即可,直到当前层为空
class Solution: # 返回二维列表[[1,2],[4,5]] def Print(self, pRoot): # write code here if pRoot is None: return [] current = [] current.append(pRoot) next_layer = [] result = [] while current: for node in current: if node.left: next_layer.append(node.left) if node.right: next_layer.append(node.right) result.append([i.val for i in current]) current, next_layer = next_layer, [] return result
参考资料: