zoukankan      html  css  js  c++  java
  • 剑指offer从上往下打印二叉树python

    题目描述

    从上往下打印出二叉树的每个节点,同层节点从左至右打印。

    思路

    二叉树的层级遍历,定义一个队列和用于返回结果的list。每次遍历到一个节点时,将其从队列里pop出来,把节点的左子和右子分别放到队尾,然后把该节点的值放入结果中。

    代码

    # -*- coding:utf-8 -*-
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution:
        # 返回从上到下每个节点值列表,例:[1,2,3]
        def PrintFromTopToBottom(self, root):
            # write code here
            if not root:
                return []
            queue = [root]
            ans = []
            while queue:
                node = queue.pop(0)
                ans.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            return ans
  • 相关阅读:
    Python的logging模块
    Python中的json模块
    Python的re模块
    NoSQL简介
    单例设计模式
    基于配置文件的方式配置AOP
    重用切点表达式
    切面优先级
    返回通知、异常通知、环绕通知
    后置通知
  • 原文地址:https://www.cnblogs.com/wangzhihang/p/11792640.html
Copyright © 2011-2022 走看看