zoukankan      html  css  js  c++  java
  • 剑指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存放当前层的节点值

    人生苦短,何不用python
  • 相关阅读:
    WordCount结对项目
    第一周作业:一些感想
    第一次作业
    Spring Cloud 微服务实战笔记
    解决jest处理es模块
    领域驱动设计(DDD:Domain-Driven Design)
    测试
    whistle
    日记(2018-11-07)
    ubuntu中使用机密数据Secrets
  • 原文地址:https://www.cnblogs.com/yqpy/p/9751174.html
Copyright © 2011-2022 走看看