【LeetCode】面试题32-1. 从上到下打印二叉树
题目:
思路:
该题目应该属于Easy类型,利用队列实现层次遍历或者广度优先搜索(BFS)。这里利用list的头插入功能模拟队列。
代码:
Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
q = []
q.append(root)
while q:
tmp = q.pop()
if tmp is not None:
res.append(tmp.val)
if tmp.left is not None:
q.insert(0, tmp.left)
if tmp.right is not None:
q.insert(0, tmp.right)
return res