BFS模板的应用。
总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html
class Solution(object):
# 层序模板,加个标记用来判断temp的正反序即可。
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
ans = []
stack = [root]
flag = 1
while stack:
sizeStack = len(stack)
temp = []
for i in range(sizeStack):
node = stack.pop(0)
temp.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
if flag:
ans.append(temp)
flag = 0
else:
ans.append(temp[::-1])
flag = 1
return ans