把二叉树打印成多行 -python

思路:跟上一篇的之字形打印思路类似,只不过不用隔层翻转打印

# -*- 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 []
        curLayer = [pRoot]
        res = []
        while curLayer:
            nextLayer = []
            tmp = []
            for node in curLayer:
                tmp.append(node.val)
                if node.left:
                    nextLayer.append(node.left)
                if node.right:
                    nextLayer.append(node.right)
            curLayer = nextLayer
            res.append(tmp)
        return res
posted @ 2019-08-13 08:50  Dolisun  阅读(231)  评论(0编辑  收藏  举报