概述
102. Binary Tree Level Order Traversal
Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]
. -1000 <= Node.val <= 1000
1. BFS广度优先 解法一
level是当前关卡中的节点列表。继续将这些节点的值列表附加到下一个级别(孩子)中的所有节点ans,然后更新level,直到它达到一个空级别。Python 的列表推导使得以简洁的方式处理许多条件变得更加容易。
def levelOrder(self, root):
if not root:
return []
ans, level = [], [root]
while level:
ans.append([node.val for node in level])
temp = []
for node in level:
temp.extend([node.left, node.right])
level = [leaf for leaf in temp if leaf]
return ans
2. BFS 简化解法二
def levelOrder(self, root):
ans, level = [], [root]
while root and level:
ans.append([node.val for node in level])
LRpair = [(node.left, node.right) for node in level]
level = [leaf for LR in LRpair for leaf in LR if leaf]
return ans
3. BFS 简化解法三
def levelOrder(self, root):
ans, level = [], [root]
while root and level:
ans.append([node.val for node in level])
level = [kid for n in level for kid in (n.left, n.right) if kid]
return ans
参考
https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33464/5-6-lines-fast-python-solution-(48-ms)
最后
以上就是安详超短裙为你收集整理的算法: 二叉树级顺序遍历 (3种解法)102. Binary Tree Level Order Traversal102. Binary Tree Level Order Traversal1. BFS广度优先 解法一2. BFS 简化解法二3. BFS 简化解法三参考的全部内容,希望文章能够帮你解决算法: 二叉树级顺序遍历 (3种解法)102. Binary Tree Level Order Traversal102. Binary Tree Level Order Traversal1. BFS广度优先 解法一2. BFS 简化解法二3. BFS 简化解法三参考所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复