从上往下打印二叉树(python)

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。
 1 class Solution:
 2     # 返回从上到下每个节点值列表,例:[1,2,3]
 3     def PrintFromTopToBottom(self, root):
 4         # write code here
 5         if root==None:
 6             return []
 7         queue=[]
 8         queue.append(root)
 9         i=0
10         while i<len(queue):
11             root=queue[i]
12             queue[i]=root.val
13             if root.left:
14                 queue.append(root.left)
15             if root.right:
16                 queue.append(root.right)
17             i+=1
18         return queue

猜你喜欢

转载自www.cnblogs.com/NPC-assange/p/12020666.html