- tobeprint记录该层节点还有多少要打印的,当tobeprint == 0 时,该层打印完毕
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回二维列表[[1,2],[4,5]] def Print(self, pRoot): # write code here if not pRoot:return '' queue = [pRoot] helper = [] tobeprint = 1 nextlevel = 0 res = [] while queue: if queue[0].left: queue.append(queue[0].left) nextlevel += 1 if queue[0].right: queue.append(queue[0].right) nextlevel += 1 tobeprint -= 1 helper.append(queue[0].val) queue.pop(0) if tobeprint == 0: res.append(helper) helper = [] tobeprint = nextlevel nextlevel = 0 return res