作者: 负雪明烛
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)的更多相关文章

  1. 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 ...

  2. (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 ...

  3. 【LeetCode】1007. Minimum Domino Rotations For Equal Row 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历一遍 日期 题目地址:https://leetc ...

  4. 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. 515 Find Largest Value in Each Tree Row 在每个树行中找最大值

    在二叉树的每一行中找到最大的值.示例:输入:           1         /  \        3   2       /  \    \        5   3    9 输出: [ ...

  6. 【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 ...

  7. 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 ...

  8. 【LeetCode】952. Largest Component Size by Common Factor 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 并查集 日期 题目地址:https://leetco ...

  9. 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...

随机推荐

  1. docker可视化管理Portainer

    Portainer是一款轻量级docker容器管理平台,占用资源少,支持集群,支持权限分配. $ docker volume create portainer_data$ docker run -d ...

  2. Shell $()、${}、$[]、$(())

    目录 Shell中的 $().${}.$[].$(()) $().${} 替换 ${} 变量内容的替换.删除.取代 数组 $[].$(()) 运算符 Shell中的 $().${}.$[].$(()) ...

  3. 基于python win32setpixel api 实现计算机图形学相关操作

    最近读研期间上了计算机可视化的课,老师也对计算机图形学的实现布置了相关的作业.虽然我没有系统地学过图形可视化的课,但是我之前逆向过一些游戏引擎,除了保护驱动之外,因为要做透视,接触过一些计算机图形学的 ...

  4. 疯了吧!这帮人居然用 Go 写“前端”?(一)

    作者 | 郑嘉涛(羣青) 来源 | 尔达 Erda 公众号 ​ 无一例外,谈到前后端分离"必定"是 RESTful API,算是定式了.但我们知道 REST 在资源划分上的设计总是 ...

  5. 在JTable单元格上 加入组件,并赋予可编辑能力 [转]

    表格(单元格放置组件) 对于JTable单元格的渲染主要是通过两个接口来实现的,一个是TableCellRenderer另一个是TableCellEditor,JTable默认是用的是DefaultC ...

  6. HTML5 之 FileReader 的使用 (二) (网页上图片拖拽并且预显示可在这里学到) [转载]

    转载至 : http://www.360doc.com/content/14/0214/18/1457948_352511645.shtml FileReader 资料(英文): https://de ...

  7. Android 高级UI组件(三)

    一.popupWindow 1.AlertDialog和PopupWindow最关键的区别是AlertDialog不能指定显示位置,只能默认显示在屏幕最中间(当然也可以通过设置WindowManage ...

  8. Gradle入门及SpringBoot项目构建

    https://blog.csdn.net/qq_27520051/article/details/90384483 一.介绍 Gradle 是一种构建工具,它抛弃了基于XML的构建脚本,取而代之的是 ...

  9. final&static

    final 1.final修饰类,那么该类不能有子类,那么也就没有子类重写父类的方法,也就没有多态 2.final修饰成员变量,那么成员变量要么显式赋值(用第一种),要么在构造方法中赋值 无论哪一种, ...

  10. zabbix之监控MySQL

    #:先配置MySQL的主从 #:安装Percona Monitoring Plugins (地址:https://www.percona.com/downloads/)#:我安在从库,监控哪个就安哪个 ...