剑指 Offer 32 - I. 从上到下打印二叉树
BFS模板的应用。
总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
res = []
stack = [root]
while stack:
sizestack = len(stack)
for i in range(sizestack):
node = stack.pop(0)
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return res