题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param root TreeNode类 # @return int整型一维数组 import queue #定义队列的对象q q = queue.Queue() class Solution: def PrintFromTopToBottom(self , root: TreeNode) -> List[int]: # write code here if not root: return [] #使用queue模块定义队列 #将root节点存入队列 q.put(root) res = [ ] #当队列不为空的时候,取出队列的第一个元素 while not q.empty(): cur=q.get() #res中添加val的值,如果存在左节点,放入队列, res.append(cur.val) if cur.left: q.put(cur.left) #如果存在右节点,放入队列 if cur.right: q.put(cur.right) return res