【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 ...
随机推荐
- LetNet、Alex、VggNet分析及其pytorch实现
简单分析一下主流的几种神经网络 LeNet LetNet作为卷积神经网络中的HelloWorld,它的结构及其的简单,1998年由LeCun提出 基本过程: 可以看到LeNet-5跟现有的conv-& ...
- mysql 5.7 压缩包安装教程
前言 : 避免之前装的MySQL影响 首先进入dos窗口执行 sc delete mysql 删除已有的mysql服务 (一) 下载MySQL5.7 版本压缩包 网址 https://de ...
- Virtual functions in derived classes
In C++, once a member function is declared as a virtual function in a base class, it becomes virtual ...
- Java实现邮件收发
一. 准备工作 1. 传输协议 SMTP协议-->发送邮件: 我们通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器) POP3协议-->接收邮件: 我 ...
- 如何在linux 上配置NTP 时间同步?
故障现象: 有些应用场景,对时间同步的要求严格,需要用到NTP同步,如何在linux上配置NTP时间同步? 解决方案: 在linux 上配置NTP 时间同步,具休操作步骤,整理如下: 1.安装软件包( ...
- Classs类
Classs类如何获得 获得Class对象 方式一: 通过Object类中的getClass()方法 方式二: 通过 类名.class 获取到字节码文件对象( 方式三: 通过Class类中的方法(将类 ...
- java 动态代理—— Mybaties 拦截器链基本原理实现
1.摘要 Mybaties 中有个分页插件,之前有特意的去了解了一下原理 :https://www.cnblogs.com/jonrain0625/p/11168247.html,从了解中得知分页插件 ...
- 【HarmonyOS】【DevEco Studio】NOTE04:How to Jump to a Page(页面间的跳转)
页面创建与基本设置 创建页面 创建两个新页面,分别为AbilityPage1.AbilityPage2 设置页面基本内容 以AbilityPage1为例 导包 import com.example.m ...
- 使用 scipy.fft 进行Fourier Transform:Python 信号处理
摘要:Fourier transform 是一个强大的概念,用于各种领域,从纯数学到音频工程甚至金融. 本文分享自华为云社区<使用 scipy.fft 进行Fourier Transform:P ...
- 车载以太网第二弹 | 测试之实锤-物理层PMA测试实践
前言 本期先从物理层"PMA测试"开始,下图1为"PMA测试"的测试结果汇总图.其中,为了验证以太网通信对线缆的敏感度,特选取两组不同特性线缆进行测试对比,果然 ...