【题目】
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回:
[3,9,20,15,7]
提示:
节点总数 <= 1000
【代码】
class Solution:
def levelOrder(self, root: TreeNode) -> List[int]:
ans=[]
if not root:
return ans
queue=[root]
while queue:
root=queue.pop(0)
ans.append(root.val)
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
return ans