zoukankan      html  css  js  c++  java
  • 剑指offer——python【第59题】按之子形顺序打印二叉树

    题目描述

    请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

    解题思路

    这道题其实是分层打印二叉树的进阶版,唯一的不同就是偶数层是列表倒序,奇数层是列表正序;只要在上道题目代码的基础上添加一个判断符,判断是奇数层还是偶数层

    代码

    class Solution:
        def Print(self, pRoot):
            # write code here
            result = []
            queue = []
            if pRoot == None:
                return result
            queue.append(pRoot)
            oddLevel = True
            while queue:
                result_layer = []
                nextLayernodeList = []
                oddLevel = not oddLevel
                for node in queue:
                    result_layer.append(node.val)
                    if node.left != None:
                        nextLayernodeList.append(node.left)
                    if node.right != None:
                        nextLayernodeList.append(node.right)
                queue = nextLayernodeList
                result.append(result_layer[::-1]) if oddLevel else result.append(result_layer)
            return result

    oddLevel就是奇数层判断符,一开始是True,后面依次是False、True、False

    人生苦短,何不用python
  • 相关阅读:
    day03--变量与基本数据类型
    day02--编程语言的分类与Python开发环境的搭建
    day01--编程与计算机组成原理
    基本数据类型操作
    python格式化字符串
    Python垃圾回收机制
    day04作业
    day03作业
    Pycharm2018安装与激活
    Python入门-python浅谈
  • 原文地址:https://www.cnblogs.com/yqpy/p/9751347.html
Copyright © 2011-2022 走看看