• 层序遍历
  • nextlevel记录下层的节点数
  • tobeprint记录本层还有几个节点未打印,当其为0时,本层打印结束,重置其为nextlevel数量,而nextlevel更新为0
  • levelnums记录现在是第几层,从而判断是从左向右打印还是相反
class Solution:
    def Print(self, pRoot):
        # write code here
        if not pRoot:return ''
        queue = [pRoot]
        helper = []
        tobeprint = 1
        nextlevel = 0
        res = []
        levelnums = 0
        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:
                levelnums += 1 
                if levelnums % 2 == 1:
                    res.append(helper) 
                else :
                    helper = helper[::-1]
                    res.append(helper)
                helper = []
                tobeprint = nextlevel
                nextlevel = 0
        return res