当前位置: 首页 > 后端技术 > Python

LeetCode - 0102. 二叉树的层次遍历【Python】

时间:2023-03-26 02:01:48 Python

力扣|.(即,从左到右,逐级)。例如:给定二叉树[3,9,20,null,null,15,7],3/\920/\157返回其层序遍历为:[[3],[9,20],[15,7]]问题链接给定一棵二叉树,返回该层遍历的节点值。(即逐层,从左到右访问所有节点)。例如:给定一棵二叉树:[3,9,20,null,null,15,7],3/\920/\157返回其层次遍历结果:[[3],[9,20],[15,7]]思路BFS方案一:非递归当队列不为空时:当前层打印循环:队列第一个元素出队,记录为node在temp末尾添加node.val如果左边(右)子节点不为空,则将左(右)子节点加入队列,将当前temp中的所有元素加入到res中时间复杂度:O(n),其中n为二进制中的节点数树。空间复杂度:O(n),其中n是二叉树中的节点数。Python3代码#定义一个二叉树节点。#classTreeNode:#def__init__(self,x):#self.val=x#self.left=None#self.right=Noneclass解决方案:deflevelOrder(self,root:TreeNode)->List[List[int]]:#解决方案一:非递归importcollectionsifnotroot:return[]res,q=[],collections.deque()q.append(root)whileq:#输出是二维数组temp=[]forxinrange(len(q)):node=q.popleft()temp.append(node.val)ifnode.left:q.append(node.left)ifnode.right:q.append(node.right)res.append(temp)returnres解法二:递交Python3代码#定义一个二叉树节点。#classTreeNode:#def__init__(self,x):#self.val=x#self.left=None#self.right=Noneclass解决方案:deflevelOrder(self,root:TreeNode)->List[List[int]]:#解决方案二:递归res=[]defhelper(root,depth):ifnotroot:returniflen(res)==depth:res.append([])res[depth].append(root.val)helper(root.left,depth+1)helper(root.right,depth+1)helper(root,0)returnresGitHub链接Python