python解法Queue容器实现bfs

#熟悉Queue容器的 的 .put() .get() .empty()用法
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import Queue  #python2为import Queue  / python3中为 import queue
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
            return []
        q=Queue.Queue()
        q.put(root)
        res=[]
        while not q.empty():
            node=q.get()
            res.append(node.val)
            if node.left:
                q.put(node.left)
            if node.right:
                q.put(node.right)
        return res
全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 16:22
主包是26应届生,投大厂简历一直过不了初筛,想问问大家有必要花钱改简历吗
Java抽象带篮子:我之前专门发个帖子说不要付费改简历的,里面还详细写了简历怎么写,你可以去看看
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务