[劍指Offer]從上往下打印二叉樹

本文首發(fā)于我的個人博客Suixin’s Blog
原文: https://suixinblog.cn/2019/03/target-offer-print-from-top-to-bottom-binary-tree.html  作者: Suixin

題目描述

從上往下打印出二叉樹的每個節(jié)點,同層節(jié)點從左至右打印。

解題思路

二叉樹的層次遍歷,使用隊列來實現(xiàn)。見二叉樹的七種遍歷方法。

代碼

Python(2.7.3)

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回從上到下每個節(jié)點值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        l = []
        if root is None:
            return l
        queue = []
        queue.append(root)
        while queue:
            node = queue.pop(0)
            l.append(node.val)
            if node.left is not None:
                queue.append(node.left)
            if node.right is not None:
                queue.append(node.right)
        return l

運行時間:27ms
占用內(nèi)存:5728k

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容