当前位置:网站首页>LeetCode 515(C#)
LeetCode 515(C#)
2022-07-07 15:38:00 【有趣就行】
题目
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:
输入: root = [1,2,3]
输出: [1,3]
代码
- DFS
public class Solution
{
public IList<int> LargestValues(TreeNode root)
{
List<int> list = new List<int>();
Dfs(list, root, 0);
return list;
}
private void Dfs(IList<int> list, TreeNode node, int depth)
{
if (node == null) return;
if (depth >= list.Count) list.Add(node.val);
else list[depth] = Math.Max(list[depth], node.val);
Dfs(list, node.left, depth + 1);
Dfs(list, node.right, depth + 1);
}
}
- BFS
public class Solution
{
public IList<int> LargestValues(TreeNode root)
{
List<int> list = new List<int>();
Queue<TreeNode> queue = new Queue<TreeNode>();
if (root != null) queue.Enqueue(root);
while (queue.Count > 0)
{
(int sz, int ans) = (queue.Count, int.MinValue);
for (int i = 0; i < sz; i++)
{
var t = queue.Dequeue();
ans = Math.Max(ans, t.val);
if (t.left != null) queue.Enqueue(t.left);
if (t.right != null) queue.Enqueue(t.right);
}
list.Add(ans);
}
return list;
}
}
边栏推荐
- DNS series (I): why does the updated DNS record not take effect?
- Lex & yacc of Pisa proxy SQL parsing
- The computer cannot add a domain, and the Ping domain name is displayed as the public IP. What is the problem? How to solve it?
- 【视频/音频数据处理】上海道宁为您带来Elecard下载、试用、教程
- 防火墙系统崩溃、文件丢失的修复方法,材料成本0元
- [Seaborn] combination chart: pairplot and jointplot
- LeetCode 1626. 无矛盾的最佳球队 每日一题
- With the latest Alibaba P7 technology system, mom doesn't have to worry about me looking for a job anymore
- Blue Bridge Cup final XOR conversion 100 points
- Is AI more fair than people in the distribution of wealth? Research on multiplayer game from deepmind
猜你喜欢

Seaborn数据可视化

Biped robot controlled by Arduino

Sator推出Web3游戏“Satorspace” ,并上线Huobi

QT中自定义控件的创建到封装到工具栏过程(二):自定义控件封装到工具栏

redis主从、哨兵主备切换搭建一步一步图解实现

麒麟信安携异构融合云金融信创解决方案亮相第十五届湖南地区金融科技交流会

PLC: automatically correct the data set noise, wash the data set | ICLR 2021 spotlight

Linux 安装mysql8.X超详细图文教程

SlashData开发者工具榜首等你而定!!!

Leetcode brush questions day49
随机推荐
鲲鹏开发者峰会2022 | 麒麟信安携手鲲鹏共筑计算产业新生态
LeetCode 1626. 无矛盾的最佳球队 每日一题
LeetCode 300. 最长递增子序列 每日一题
电脑无法加域,ping域名显示为公网IP,这是什么问题?怎么解决?
LeetCode 403. Frog crossing the river daily
[source code interpretation] | source code interpretation of livelistenerbus
Mrs offline data analysis: process OBS data through Flink job
智慧物流平台:让海外仓更聪明
[image sensor] correlated double sampling CDs
第二十四届中国科协湖南组委会调研课题组一行莅临麒麟信安调研考察
99% 用户在 Power BI 云端报表常犯错误
LeetCode 213. Home raiding II daily question
Lex & yacc of Pisa proxy SQL parsing
From Devops to mlops: how do it tools evolve to AI tools?
《产品经理必读:五种经典的创新思维模型》的读后感
QT中自定义控件的创建到封装到工具栏过程(二):自定义控件封装到工具栏
Flask搭建api服务
Blue Bridge Cup final XOR conversion 100 points
Solidity 开发环境搭建
邮件服务器被列入黑名单,如何快速解封?