今天是day12
第一题为二叉树的层序遍历
"遍历长度法"
"借用队列,将root加入其中"
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
queue = collections.deque([root])
result = []
while queue:
level = []
"遍历queue"
for _ in range(len(queue)):
"左弹出并将值加入level中"
cur = queue.popleft()
level.append(cur.val)
"开始层序遍历"
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
result.append(level)
return result
"递归法暂且不知何意"
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
levels = []
self.helper(root,0,levels)
return levels
def helper(self,node,level,levels):
if not node:
return
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
self.helper(node.left,level+1,levels)
self.helper(node.right,level+1,levels)
标签:cur,level,self,queue,levels,day12,append
From: https://www.cnblogs.com/leisure535/p/18242635