剑指offer——python【第60题】把二叉树打印成多行

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。#类似于二维列表[[1,2],[4,5]]

解题思路

其实这倒题和其他类似的题有所区别,这里是分层打印,把每层的节点值放在同一个列表,然后再放到一个大列表里面;

那么关键就在于怎样把每层的节点值从左到右依次取出来?有一个办法,就是把当前层的所有节点的全部子节点都存到一个列表中(这个列表每次都要更新),只要遍历这个列表,取出值就可以了

代码

class Solution:
    # 返回二维列表[[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        result = []
        nodeList = []
        if pRoot == None:return result
        nodeList.append(pRoot)
        while nodeList:
            result_layer = []
            nextLayernodeList = []
            for node in nodeList:
                result_layer.append(node.val)
                if node.left:nextLayernodeList.append(node.left)
                if node.right:nextLayernodeList.append(node.right)
            nodeList = nextLayernodeList
            result.append(result_layer)
        return result

nodeList存放当前层的节点;nextLayernodeList存放下一层的节点;result_layer存放当前层的节点值

猜你喜欢

转载自www.cnblogs.com/yqpy/p/9751174.html