本文首發(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