[剑指Offer]从上往下打印二叉树

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

题目描述

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

解题思路

二叉树的层次遍历,使用队列来实现。见二叉树的七种遍历方法。

代码

Python(2.7.3)

# -*- 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
        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
占用内存:5728k

你可能感兴趣的:([剑指Offer]从上往下打印二叉树)