【剑指offer】把二叉树打印成多行(python)

  1. 思路类似“从上往下打印二叉树”,也是用队列
  2. 有个小点,tmp需要判断是否为空。因为多遍历了一遍,最后一遍的时候tmp=[]
# -*- 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
        result = []
        queue = []
        queue.append(pRoot)
        while queue:
            num = len(queue)
            tmp = []
            for i in range(num):
                node = queue.pop(0)
                if node is None:
                    continue
                tmp.append(node.val)
                queue.append(node.left)
                queue.append(node.right)
            if tmp:
                result.append(tmp)
        return result