作者: 负雪明烛
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. R语言与医学统计图形-【25】ggplot图形分面

    ggplot2绘图系统--图形分面 ggplot2的分面faceting,主要有三个函数: facet_grid facet_wrap facet_null (不分面) 1. facet_grid函数 ...

  2. 执行脚本source 和 . 和sh 的区别是什么

    "source"和"."的功能是一样的,可以调用脚本,并将脚本里的函数也传递到当前的脚本或者解释器中,即不会开启新的bash而是在当前bash中运行. &quo ...

  3. 基本绘图函数:plot的使用

    注意:"##"后面是程序输出结果 例如: par("bg") # 命令 ## [1] "white" # 结果 基本绘图函数: plot:散 ...

  4. mysql-日期时间函数大全

    DAYOFWEEK(date)  返回日期date是星期几(1=星期天,2=星期一,--7=星期六,ODBC标准)mysql> select DAYOFWEEK('1998-02-03');  ...

  5. 动态生成多个选择项【c#】

    <asp:CheckBoxList ID="cbxLabelList" runat="server" RepeatColumns="10&quo ...

  6. sed 修改文件

    总结 正确的修改进文件命令(替换文件内容):sed -i "s#machangwei#mcw#g" mcw.txt 正确的修改追加进文件命令(追加文件内容):sed -i &quo ...

  7. 大数据学习day31------spark11-------1. Redis的安装和启动,2 redis客户端 3.Redis的数据类型 4. kafka(安装和常用命令)5.kafka java客户端

    1. Redis Redis是目前一个非常优秀的key-value存储系统(内存的NoSQL数据库).和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list ...

  8. 【编程思想】【设计模式】【创建模式creational】Pool

    Python版 https://github.com/faif/python-patterns/blob/master/creational/pool.py #!/usr/bin/env python ...

  9. my39_InnoDB锁机制之Gap Lock、Next-Key Lock、Record Lock解析

    MySQL InnoDB支持三种行锁定方式: 行锁(Record Lock):锁直接加在索引记录上面,锁住的是key. 间隙锁(Gap Lock): 锁定索引记录间隙,确保索引记录的间隙不变.间隙锁是 ...

  10. 【Spring Framework】Spring IOC详解及Bean生命周期详细过程

    Spring IOC 首先,在此之前,我们就必须先知道什么是ioc,ioc叫做控制反转,也可以称为依赖注入(DI),实际上依赖注入是ioc的另一种说法, 1.谁控制谁?: 在以前,对象的创建和销毁都是 ...