当前位置:网站首页>LeetCode 515(C#)
LeetCode 515(C#)
2022-07-07 19:17:00 【Just be interesting】
subject
Given the root node of a binary tree root , Please find the maximum value of each layer in the binary tree .
Example 1:
Input : root = [1,3,2,5,3,null,9]
Output : [1,3,9]
Example 2:
Input : root = [1,2,3]
Output : [1,3]
Code
- 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;
}
}
边栏推荐
- [information security laws and regulations] review
- 虚拟数字人里的生意经
- cmd命令进入MySQL时报服务名或者命令错误(傻瓜式教学)
- DeSci:去中心化科学是Web3.0的新趋势?
- unity2d的Rigidbody2D的MovePosition函数移动时人物或屏幕抖动问题解决
- 基于图像和激光的多模态点云融合与视觉定位
- 解决远程rviz报错问题
- Continuous test (CT) practical experience sharing
- Creative changes brought about by the yuan universe
- Initial experience of cache and ehcache "suggestions collection"
猜你喜欢

Charles+Postern的APP抓包

Three forms of multimedia technology commonly used in enterprise exhibition hall design

Redis cluster and expansion

二叉树的基本概念和性质

【软件测试】从企业版BOSS直聘,看求职简历,你没被面上是有原因的

博睿数据入选《2022爱分析 · IT运维厂商全景报告》

Realize payment function in applet

2022.07.02

Differences between rip and OSPF and configuration commands

Redis
随机推荐
炒股如何开户?请问一下手机开户股票开户安全吗?
Micro service remote debug, nocalhost + rainbow micro service development second bullet
POJ 1182: food chain (parallel search) [easy to understand]
数据验证框架 Apache BVal 再使用
2022.07.04
Will low code help enterprises' digital transformation make programmers unemployed?
How many are there (Lua)
Reject policy of thread pool
高温火烧浑不怕,钟薛高想留清白在人间
Thread factory in thread pool
SlashData开发者工具榜首等你而定!!!
【MIME笔记】
ES6 note 1
DeSci:去中心化科学是Web3.0的新趋势?
网易云信参与中国信通院《实时音视频服务(RTC)基础能力要求及评估方法》标准编制...
6.关于jwt
Creative changes brought about by the yuan universe
Uvalive – 4621 CAV greed + analysis "suggestions collection"
Flipping game (enumeration)
10 schemes to ensure interface data security