把二叉树打印成多行

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路
给定一个二叉树样例:
这里写图片描述 以上图的二叉树样例来说,需要说明的点是,题目需要的输出是形如[[1], [2,3], [4,5,6,7]]。
# -*- 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 []
        resultList = []
        curLayer = [pRoot]
        while curLayer:
            curList = []
            nextLayer = []
            for node in curLayer:
                curList.append(node.val)
                if node.left:
                    nextLayer.append(node.left)
                if node.right:
                    nextLayer.append(node.right)
            resultList.append(curList)
            curLayer = nextLayer
        return resultList
原文地址:https://www.cnblogs.com/tianqizhi/p/9690203.html