从上往下打印出二叉树的每个节点,同层节点从左至右打印。
class Solution:
def PrintFromTopToBottom(self, root):
# write code here
l=[]
if not root:
return []
q=[root]
while 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
每次循环打印根节点
使用一个列表来存储二叉树的每一层即将进行遍历的节点,而且每次遍历过该节点,把该节点删除,并且把新的根节点加进去。
使用另一个列表来存储层次遍历的结果。