Leetcode - 广度优先遍历
来源:互联网 发布:vm虚拟机没有网络 编辑:程序博客网 时间:2024/05/29 07:14
> 基础
1. 广度遍历优先是从给定的root节点开始,逐层次的向下访问各个节点;
2. 实现的方式是通过队列的先进先出,将从root节点开始的左孩子和右孩子压入到队列中,并顺序取出;
3. 由于是用队列实现,因此不存在用递归实现的方式。
下面是基本的广度遍历优先算法:
def breadthFirstSearch(root): queue = [] queue.append(root) while queue: node = queue[0] queue.pop(0) print ('%d ' % node.data) if node.left: queue.append(node.left) if node.right: queue.append(node.right)
> Leetcode - Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7]]Note:这是一道二叉树的广度优先遍历练习题,不同之处在于要分辨出每个Node所在的深度,并给出每个深度所有Node的集合。解题思路有两种,一种是使用两个队列,分别为主队列和副队列,循环主队列里的所有节点,并把所有的孩子放在副队列中。这样当主队列为空时,把副队列赋给主队列,并清空副队列,就进入到下一级深度的循环。还有一种是使用flag,在root结点后加入flag,然后每次访问到flag的时候,就意味着访问到了该深度所有的Node,并且下一个深度的所有Node都加入到了队列中,这时再加入一个flag,依此循环。这里使用第二种方法。
Answer:
def levelOrder(root): if root is []: return [] flag = TreeNode(65536) queue, line, res = [], [], [] queue.append(root) queue.append(flag) while queue: node = queue[0] queue.pop(0) if node.val is not 65536: line.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) else: res.append(line) if not queue: return res queue.append(flag) line = []
0 0
- Leetcode - 广度优先遍历
- Leetcode 之BFS广度优先遍历
- 【广度优先遍历】leetcode - Word Ladder II
- 广度优先遍历BFS
- 广度优先遍历
- 图--广度优先遍历
- 图广度优先遍历
- 广度优先遍历
- 广度优先遍历-示例
- 广度优先遍历代码
- 广度优先遍历
- 广度优先遍历
- 广度优先遍历
- 广度优先遍历
- BFS广度优先遍历
- 广度优先遍历
- 图遍历-广度优先
- java广度优先遍历
- LeetCode 100 Maximum Subarray
- Linux 设备驱动 一
- 架构师趣味回答 java
- CSDN博客导出(二) - 解析HTML
- Android中利用Handler实现消息的分发机制(二)
- Leetcode - 广度优先遍历
- nginx 常用配置
- Linux中iptables设置详细
- Objective-C 内存管理
- android actionbar自定义样式so easy(一)
- Android APK反编译详解(附图)
- linux下IPTABLES配置详解
- QAxContainerd.lib(qaxbase.obj) : error LNK2038: 检测到“_ITERATOR_DEBUG_LEVEL”的不匹配项: 值“2”不匹配值“0”(DlgCont
- typedef int(init_fnc_t) (void) 和 typedef int(*init_fnc_t) (void)