- 921. Minimum Add to Make Parentheses Valid 使括号有效的最少添加
- 915. Partition Array into Disjoint Intervals 分割数组
- 932. Beautiful Array 漂亮数组
- 940. Distinct Subsequences II 不同的子序列 II
题目地址:https://leetcode.com/problems/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).
Forexample:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
层次遍历二叉树。
BFS使用队列,把每个还没有搜索到的点依次放入队列,然后再弹出队列的头部元素当做当前遍历点。BFS总共有两个模板:
1、 如果不需要确定当前遍历到了哪一层,BFS模板如下;
while queue 不空:
cur = queue.pop()
for 节点 in cur的所有相邻节点:
if 该节点有效且未访问过:
queue.push(该节点)
1 2 3 4 5
1、 如果要确定当前遍历到了哪一层,BFS模板如下这里增加了level表示当前遍历到二叉树中的哪一层了,也可以理解为在一个图中,现在已经走了多少步了size表示在当前遍历层有多少个元素,也就是队列中的元素数,我们把这些元素一次性遍历完,即把当前层的所有元素都向外走了一步;
level = 0
while queue 不空:
size = queue.size()
while (size --) {
cur = queue.pop()
for 节点 in cur的所有相邻节点:
if 该节点有效且未被访问过:
queue.push(该节点)
}
level ++;
1 2 3 4 5 6 7 8 9 10
上面两个是通用模板,在任何题目中都可以用,是要记住的!
本题要求二叉树的层次遍历,所以同一层的节点应该放在一起,故使用模板二。
使用队列保存每层的所有节点,每次把队列里的原先所有节点进行出队列操作,再把每个元素的非空左右子节点进入队列。因此即可得到每层的遍历。
Python代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
if not root: return res
queue = collections.deque()
queue.append(root)
while queue:
level = []
for i in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(level)
return res
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
本题使用 DFS 同样能做。由于题目要求每一层的节点都是从左到右遍历,因此递归时也要先递归左子树、再递归右子树。
DFS做本题的主要问题是: DFS 不是按照层次遍历的。为了让递归的过程中同一层的节点放到同一个列表中,在递归时要记录每个节点的深度 level。递归到新节点要把该节点放入 level 对应列表的末尾。
当遍历到一个新的深度 level,而最终结果 res 中还没有创建 level 对应的列表时,应该在 res 中新建一个列表用来保存该 level 的所有节点。
Python 代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
self.level(root, 0, res)
return res
def level(self, root, level, res):
if not root: return
if len(res) == level: res.append([])
res[level].append(root.val)
if root.left: self.level(root.left, level + 1, res)
if root.right: self.level(root.right, level + 1, res)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
C++代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
dfs(res, root, 0);
return res;
}
void dfs(vector<vector<int>>& res, TreeNode* root, int level) {
if (!root) return;
if (level >= res.size())
res.push_back(vector<int>());
res[level].push_back(root->val);
dfs(res, root->left, level + 1);
dfs(res, root->right, level + 1);
}
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有
本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发
我对以下树的术语感到困惑,我一直在研究树,但无法区分这些树: a) 完全二叉树 b) 严格二叉树 c) 完整二叉树 请帮我区分这些树。这些树何时何地在数据结构中使用? 最佳答案 完美的树:
我正在检查数字系统并在它们之间进行转换。 我认为十六进制值比二进制使用更少的位,这是有道理的,但最终十六进制值不是存储为位吗?这似乎最终打败了目的。 最佳答案 几乎在所有情况下,计算机使用的所有数据最
任何人都可以在 Cudd 包上指出一些好的 Material 吗?我在这里寻找一些简洁的事情。位于 http://vlsi.colorado.edu/~fabio/CUDD/ 的那个似乎没有对此事做出
我正在检查数字系统并在它们之间进行转换。 我认为十六进制值比二进制使用更少的位,这是有道理的,但最终十六进制值不是存储为位吗?这似乎最终打败了目的。 最佳答案 几乎在所有情况下,计算机使用的所有数据最
在我的应用程序中,我需要序列化一个包含任意数据类型的向量,在本例中是一个 Doubles 列表。为了序列化我正在导入 Data.Vector.Binary 的向量。 在 GHCi 中加载模块时出现以下
我尝试通过 sqlalchemy 将二进制文件存储到 postgresql 中,并从客户端上传文件。 对错误消息的一点谷歌把我带到 this source file :“包装的对象不是字节或缓冲区,这
我从表(源)中执行 INSERT SELECT,其中每列都是 VARCHAR 数据类型。 其中一列存储二进制数据,例如 '0003f80075177fe6' 我插入的目标表具有相同的列,但具有正确的数
无法简单地将二进制文件复制到 Linux 机器。哇!我今天觉得很蠢!以下是从默认镜像和 utah.edu 下载的二进制包的 tar.gz 中的文件列表: -rwxr-xr-x 1 ec2-user e
我正在阅读关于 Binary search 的不同 Material ,我不清楚它是一个贪婪的二进制文件(在我看来它不是)或者,它可以是一个具有某些特定实现的贪婪算法吗? 如果它可以是贪心的,它有什么
我见过这样写的代码: ifstream fin; fin.open("largefile.dat", ifstream::binary | ifstream::in); 现在这让我感到困惑,上面的代码
binary(10) vs char(10)character set binary有什么区别? 还有varbinary(10) vs varchar(10)字符集二进制? 它们在所有 MySQL 引
binary(10) vs char(10)character set binary有什么区别? 还有varbinary(10) vs varchar(10)字符集二进制? 它们在所有 MySQL 引
我尝试将一些数据插入到从 mysql 中的另一个表检索的表中,该表的数据类型为 BINARY(20)。 提取的数据位于变量$binary['hash']; /l÷ˆ8Ô]¿\µK prepare("I
在我的一个站点上,我有一个主用户表,其中包含每个用户的唯一用户 ID、电子邮件地址、密码等。 我需要开始跟踪很多与每个用户相关的二进制标志,比如他们是否确认了他们的电子邮件,他们是否发布了消息,他们是
在最近 SO discussion我展示了一个需要修剪顶点 6 和 7 的二叉分类树: 下面是我使用的代码: KaryTree[9, 2, VertexLabels -> {1 -> "Blood
请解释一下,对于以下查询,在 Mysql 中哪个会更快? SELECT * FROM `userstatus` where BINARY Name = 'Raja' [OR] SELECT * FRO
我通过定义 ngram_vectorizer = CountVectorizer(binary=True) 和 ngram_vectorizer = CountVectorizer(binary=Fa
在 C++ 中搜索文件读取示例时,我注意到许多示例使用 std::ios::binary 与 std::ifstream::binary std::ios::beg 与 your_file_strea
我在这里和其他论坛上看到过旧帖子,其代码与下面的代码类似,但无法弄清楚其中的一部分来自哪里。 let Source = Table.FromRows(Json.Document(Binary.
#include #include #define SIGBAD(signo) ((signo) = NSIG) int sigaddset(sigset_t *set, int signo
我是一名优秀的程序员,十分优秀!