【LeetCode】515. Find Largest Value in Each Tree Row 解题报告(Python & C++ & Java)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/find-largest-value-in-each-tree-row/#/description
题目描述
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
题目大意
找出二叉树每层的最大值元素。
解题方法
BFS
BFS,可以背下来了。用一个队列保存每层的节点。记录下来每层的节点数目,把这个层的遍历结束,然后找出这个层的最大值。把每层的最大值保存下来,最后返回即可。
注意,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 largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
queue = collections.deque()
res = []
queue.append(root)
while queue:
size = len(queue)
max_level = float("-inf")
for i in range(size):
node = queue.popleft()
if not node: continue
max_level = max(max_level, node.val)
queue.append(node.left)
queue.append(node.right)
if max_level != float("-inf"):
res.append(max_level)
return res
C++代码如下。C++版本的如果按照python写就会把最后一层的叶子放进去,但是python版本就没有,没看懂为啥。另外C++使用了long型最小值,这样才能避免有INT_MIN的叶子节点存在。
/**
* 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<int> largestValues(TreeNode* root) {
queue<TreeNode*> q;
vector<int> res;
q.push(root);
while (!q.empty()) {
int size = q.size();
long max_level = LONG_MIN;
for (int i = 0; i < size; i++) {
TreeNode* node = q.front(); q.pop();
if (!node) continue;
max_level = max(max_level, (long)node->val);
q.push(node->left);
q.push(node->right);
}
if (max_level != LONG_MIN)
res.push_back(max_level);
}
return res;
}
};
Java代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
if(root == null){
return ans;
}
int level;
int size;
Queue<TreeNode> tree = new LinkedList<TreeNode>();
tree.offer(root);
TreeNode curr = null;
while(!tree.isEmpty()){
level = Integer.MIN_VALUE;
size = tree.size();
for(int i = 0; i < size; i++){
curr = tree.poll();
level = Math.max(level, curr.val);
if(curr.left != null){
tree.offer(curr.left);
}
if(curr.right != null){
tree.offer(curr.right);
}
}
ans.add(level);
}
return ans;
}
}
DFS
使用DFS进行搜索代码就是层次遍历+每层取最大值。
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 largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
levels = []
self.dfs(root, levels, 0)
return [max(l) for l in levels]
def dfs(self, root, levels, level):
if not root: return
if level == len(levels): levels.append([])
levels[level].append(root.val)
self.dfs(root.left, levels, level + 1)
self.dfs(root.right, levels, level + 1)
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<int> largestValues(TreeNode* root) {
dfs(root, levels, 0);
vector<int> res;
for (int i = 0; i < levels.size(); i++) {
res.push_back(*max_element(levels[i].begin(), levels[i].end()));
}
return res;
}
private:
vector<vector<int>> levels;
void dfs(TreeNode* root, vector<vector<int>>& levels, int level) {
if (!root) return;
if (levels.size() == level) levels.push_back({});
levels[level].push_back(root->val);
dfs(root->left, levels, level + 1);
dfs(root->right, levels, level + 1);
}
};
日期
2017 年 4 月 15 日
2018 年 12 月 7 日 —— 恩,12月又过去一周了
【LeetCode】515. Find Largest Value in Each Tree Row 解题报告(Python & C++ & Java)的更多相关文章
- LN : leetcode 515 Find Largest Value in Each Tree Row
lc 515 Find Largest Value in Each Tree Row 515 Find Largest Value in Each Tree Row You need to find ...
- (BFS 二叉树) leetcode 515. Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree. Example: Input: 1 / \ 3 2 / \ \ 5 3 ...
- 【LeetCode】1007. Minimum Domino Rotations For Equal Row 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历一遍 日期 题目地址:https://leetc ...
- 515. Find Largest Value in Each Tree Row查找一行中的最大值
[抄题]: You need to find the largest value in each row of a binary tree. Example: Input: 1 / \ 3 2 / \ ...
- 515 Find Largest Value in Each Tree Row 在每个树行中找最大值
在二叉树的每一行中找到最大的值.示例:输入: 1 / \ 3 2 / \ \ 5 3 9 输出: [ ...
- 【leetcode】Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree. Example: Input: 1 / \ 3 2 / \ \ 5 3 ...
- 515. Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree. Example: Input: 1 / \ 3 2 / \ \ 5 3 ...
- 【LeetCode】952. Largest Component Size by Common Factor 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 并查集 日期 题目地址:https://leetco ...
- 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...
随机推荐
- halt
halt命令用来关闭正在运行的Linux操作系统.halt命令会先检测系统的runlevel,若runlevel为0或6,则关闭系统,否则即调用shutdown来关闭系统. 语法 halt(选项) 选 ...
- SpringBoot整合Shiro 三:整合Mybatis
搭建环境见: SpringBoot整合Shiro 一:搭建环境 shiro配置类见: SpringBoot整合Shiro 二:Shiro配置类 整合Mybatis 添加Maven依赖 mysql.dr ...
- 零基础学习java------day1------计算机基础以及java的一些简单了解
一. java的简单了解 Java是一门面向对象编程语言,不仅吸收了C++的各种优点,还摒弃了C++里难以理解的多继承.指针等概念,因此Java语言具有功能强大和简单易用两个特征.Java语言作为静态 ...
- Apache2配置文件解读
每次碰到都不知道具体的作用,所以来分析一下 配置文件结构 apache2在启动的时候自动读取/etc/apache2/apache2.conf文件的配置信息,不同的配置项按功能分布在不同的文件中,然后 ...
- mysql_取分组后的前几行值
--方法一: select a.id,a.SName,a.ClsNo,a.Score from Table1 a left join Table1 b on a.ClsNo=b.ClsNo and a ...
- oracle 执行计划的获取方法
1.用explain plan for来获取执行计划 explain plan for <sql>; select * from table(dbms_xplan.display()); ...
- oracle(创建数据库对象)
1 --创建数据库 2 --1.SYSDBA系统权限 3 startup:--启动数据库. 4 shutdown:--关闭数据库. 5 alter database[mount]|[open]|[ba ...
- Linux基础命令---mget获取ftp文件
mget 使用lftp登录mftp服务器之后,可以使用mget指令从服务器获取文件.mget指令可以使用通配符,而get指令则不可以. 1.语法 mget [-E] [-a] [- ...
- SpringAOP浅析
1.问题 问题:想要添加日志记录.性能监控.安全监测 2.最初解决方案 2.1.最初解决方案 缺点:太多重复代码,且紧耦合 2.2.抽象类进行共性设计,子类进行个性设计,此处不讲解,缺点一荣俱荣,一损 ...
- MyBatis(3):优化MyBatis配置文件
一.连接数据库的配置单独放在一个properties文件中 1,创建一个database.properties driver=com.mysql.jdbc.Driver url=jdbc:mysql: ...