这题关键在于实时更新list,先pop在加进去left和right
# -*- 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
if not root:
return []
all_list=[root]
res=[]
while all_list:
tmp=all_list.pop(0)
if tmp.left:
all_list.append(tmp.left)
if tmp.right:
all_list.append(tmp.right)
res.append(tmp.val)
return res