剑指offer全集详解python版——从上往下打印二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41679411/article/details/86484983

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

思路:

开个队列用来辅助就可以了

代码:

# -*- 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 not root:
            return []
        q=[root]
        while len(q):
            t=q.pop(0)
            l.append(t.val)
            if t.left:
                q.append(t.left)
            if t.right:
                q.append(t.right)
        return l  

猜你喜欢

转载自blog.csdn.net/weixin_41679411/article/details/86484983
今日推荐