题目
代码
执行用时:44 ms, 在所有 Python3 提交中击败了15.59% 的用户
内存消耗:16 MB, 在所有 Python3 提交中击败了5.07% 的用户
通过测试用例:34 / 34
class Solution:
def visit(self,root,depth):
if not root:
return depth
self.ans[depth].append(root.val)
return max(self.visit(root.left,depth+1),self.visit(root.right,depth+1))
def levelOrder(self, root: TreeNode) -> List[List[int]]:
self.ans=[[] for i in range(1000)]
res=self.visit(root,0)
return self.ans[:res]
【方法2】
执行用时:28 ms, 在所有 Python3 提交中击败了95.91% 的用户
内存消耗:15.2 MB, 在所有 Python3 提交中击败了74.92% 的用户
通过测试用例:34 / 34
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
queue=[root]
if not root: return []
ans=[]
while queue:
queue_size=len(queue)
temp_ans=[]
while queue_size:
queue_size-=1
temp=queue.pop(0)
temp_ans.append(temp.val)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
ans.append(temp_ans)
return ans

本文介绍了两种Python实现方式,第一种方法的时间复杂度为O(n),内存消耗适中;第二种方法优化了执行时间,仅用时28ms,且内存消耗更低。主要关注如何通过改进算法提高二叉树层序遍历的效率。
355

被折叠的 条评论
为什么被折叠?



