首页 > 代码库 > leetcode tree related problems (update continuously)
leetcode tree related problems (update continuously)
leetcode Binary Tree Level Order Traversal
这道题是要进行二叉树的层次遍历,对于层次遍历,最简单直观的办法就是进行BFS。于是我们只需要维护一个队列就可以了,队列里面的元素需要记录该节点的内容和节点所在的层,依次从队列中取出节点进行扩展就可以了。
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrder(self, root): if(root == None): return [] queue = [] queue.append((0, root)) ans = [] cur = 0 cur_nodes = [] while len(queue) != 0: level, fa = queue.pop(0) if(level == cur): cur_nodes.append(fa.val) else: ans.append(cur_nodes) cur_nodes = [] cur_nodes.append(fa.val) cur = level if fa.left != None: queue.append((level+1, fa.left)) if fa.right != None: queue.append((level+1, fa.right)) ans.append(cur_nodes) return ans
leetcode tree related problems (update continuously)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。