解题思路
使用队列分层处理
对子节点层数加1
从队列出元素时,队列的层数是非递减的,并且差值不会超过1
队列遍历完成即处理完成
102. 二叉树的层序遍历
代码
# 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[List[int]]
"""
if not root: return []
ans = []
queue = [(0, root)]
while queue:
level, tree = queue.pop(0)
if level == len(ans):
ans.append([tree.val])
else:
ans[-1].append(tree.val)
if tree.left: queue.append((level+1, tree.left))
if tree.right: queue.append((level+1, tree.right))
return ans