当前位置:网站首页>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;
}
}
边栏推荐
- 微信网页调试8.0.19换掉X5内核,改用xweb,所以x5调试方式已经不能用了,现在有了解决方案
- Short selling, overprinting and stock keeping, Oriental selection actually sold 2.66 million books in Tiktok in one month
- 如何给“不卖笔”的晨光估值?
- 2022-07-04 matlab reads video frames and saves them
- POJ 1182 :食物链(并查集)[通俗易懂]
- PV静态创建和动态创建
- Redis
- 2022-07-04 matlab读取视频帧并保存
- 最长公共前缀(leetcode题14)
- 博睿数据入选《2022爱分析 · IT运维厂商全景报告》
猜你喜欢
Reuse of data validation framework Apache bval
数据验证框架 Apache BVal 再使用
ES6 note 1
Micro service remote debug, nocalhost + rainbow micro service development second bullet
2022.07.04
[tpm2.0 principle and Application guide] Chapter 16, 17 and 18
抢占周杰伦
Zhong Xuegao wants to remain innocent in the world
Do you know all four common cache modes?
Cadre de validation des données Apache bval réutilisé
随机推荐
Golang client server login
Teach your sister to write the message queue hand in hand
LeetCode 890(C#)
Is AI more fair than people in the distribution of wealth? Research on multiplayer game from deepmind
How many times is PTA 1101 B than a
How many are there (Lua)
Where does brain hole come from? New research from the University of California: creative people's neural connections will "take shortcuts"
SD_ DATA_ RECEIVE_ SHIFT_ REGISTER
POJ 2392 Space Elevator
Hutool - lightweight DB operation solution
Creative changes brought about by the yuan universe
Business experience in virtual digital human
ip netns 命令(备忘)
2022-07-04 matlab reads video frames and saves them
Command mode - unity
The moveposition function of rigidbody2d of unity2d solves the problem of people or screen jitter when moving
Nat address translation
How to implement safety practice in software development stage
如何选择合适的自动化测试工具?
微信网页调试8.0.19换掉X5内核,改用xweb,所以x5调试方式已经不能用了,现在有了解决方案