当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
博睿数据入选《2022爱分析 · IT运维厂商全景报告》
Desci: is decentralized science the new trend of Web3.0?
Chief technology officer of Pasqual: analog quantum computing takes the lead in bringing quantum advantages to industry
[information security laws and regulations] review
Review of network attack and defense
Redis
GSAP animation library
Pasqal首席技术官:模拟量子计算率先为工业带来量子优势
Antisamy: a solution against XSS attack tutorial
如何给“不卖笔”的晨光估值?
随机推荐
Classification and application of enterprise MES Manufacturing Execution System
Teach your sister to write the message queue hand in hand
POJ 1182: food chain (parallel search) [easy to understand]
Hutool - lightweight DB operation solution
[Blue Bridge Cup training 100 questions] sort scratch from small to large. Blue Bridge Cup scratch competition special prediction programming question centralized training simulation exercise question
Borui data was selected in the 2022 love analysis - Panoramic report of it operation and maintenance manufacturers
Key points of anti reptile: identifying reptiles
Version 2.0 of tapdata, the open source live data platform, has been released
cmd命令进入MySQL时报服务名或者命令错误(傻瓜式教学)
Numpy——axis
虚拟数字人里的生意经
ip netns 命令(备忘)
LeetCode 497(C#)
2022.07.05
POJ 2392 Space Elevator
L1-019 who falls first (Lua)
Charles+drony的APP抓包
2022.07.04
Antisamy: a solution against XSS attack tutorial
解决远程rviz报错问题