此题与lc102一样。这个算法的时间复杂度是O(N),空间复杂度是O(N)。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
res, stack = [], [root]
while stack:
seg = []
for i in range(len(stack)):
tmp = stack.pop(0)
seg.append(tmp.val)
if tmp.left:
stack.append(tmp.left)
if tmp.right:
stack.append(tmp.right)
res.append(seg)
return res
PREVIOUSmq004.验证回文串
NEXTmq006.复制带随机指针的列表