首页 > 其他 > 详细

剑指offer——从上往下打印二叉树

时间:2019-11-22 15:41:38      阅读:75      评论:0      收藏:0      [点我收藏+]

题目描述

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

 

本明显的层次遍历,用queue:

# -*- 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 root ==None :
            return []
        res,queue=[],[root]
        while queue:
            tmp=queue.pop(0)
            res.append(tmp.val)
            if tmp.left:
                queue.append(tmp.left)
            if tmp.right:
                queue.append(tmp.right)
        return res

  

剑指offer——从上往下打印二叉树

原文:https://www.cnblogs.com/hit-joseph/p/11911682.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!