zoukankan      html  css  js  c++  java
  • 按之字形顺序打印二叉树 -python

    思路:之前遇到过层序打印二叉树的题,使用一个队列存储每一层的节点,当一个节点出队列时,他的左右孩子入队列。那么这个问题是在这个问题的基础上加了点限制,因此我们也可以在之前的思路上稍作修改。
    首先用curLayer作为队列存储当前层的所有节点,把这一层标记成0或者1, 再用nextLayer层存储从curLayer成出队的节点的左右孩子(这是不同点,层序打印的是放在一个队列中的,因为现在需要标记不同的层,因此不能放在一个队列里面),根据标记的0或者1进行顺序输出和反序输出。

    # -*- coding:utf-8 -*-
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution:
        def Print(self, pRoot):
            if not pRoot:
                return []
            # write code here
            curLayer = [pRoot]
            res = []
            cnt = 0
            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)
                if cnt == 0:
                    res.append(tmp)
                else:
                    res.append(tmp[::-1])
                curLayer = nextLayer
                cnt = (cnt+1) % 2
            return res
    
  • 相关阅读:
    Rabbitmq整合SpringBoot
    linux下转pdf乱码
    invalid authentication data connection reset
    谷粒商城异步编排(三十一)
    KSA运行
    安装k8s缺少模块
    ansible安装
    Rabbitmq常见的模式
    Rabbitmq入门
    谷粒商城检索服务(三十)
  • 原文地址:https://www.cnblogs.com/dolisun/p/11342847.html
Copyright © 2011-2022 走看看