首页 > 代码库 > 【leetcode】Binary Tree Level Order Traversal
【leetcode】Binary Tree Level Order Traversal
class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ret = [] if not root: return ret max_dep = 0 queue = [] p = 0 q = 1 queue.append((root,1)) while p < q: current_dep = queue[p][1] node = queue[p][0] if max_dep < current_dep: ret.append([]) max_dep = current_dep ret[current_dep - 1].append(node.val) for node in (node.left,node.right): if node: queue.append((node,current_dep + 1)) q += 1 p += 1 return ret
class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ret = [] if not root: return ret level = [root] while level: ret.append([node.val for node in level]) level = [leaf for node in level for leaf in (node.left,node.right) if leaf] return ret
class Solution(object): def do(self, p, level): if (not p): return if level >= len(self.list): self.list.append([p.val]) else: self.list[level].append(p.val) self.do(p.left, level + 1) self.do(p.right, level + 1) def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ self.list = [] self.do(root,0) return self.list
用三种方法写了一下,第二种有点意思,玩玩python了
【leetcode】Binary Tree Level Order Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。