当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
Business experience in virtual digital human
In the first half of 2022, I found 10 books that have been passed around by my circle of friends
6. About JWT
How to estimate the value of "not selling pens" Chenguang?
Antisamy: a solution against XSS attack tutorial
Seize Jay Chou
How to choose the appropriate automated testing tools?
2022.07.04
Desci: is decentralized science the new trend of Web3.0?
3.关于cookie
随机推荐
嵌入式面试题(算法部分)
coming! Gaussdb (for Cassandra) new features appear
99% of people don't know that privatized deployment is also a permanently free instant messaging software!
How to choose the appropriate automated testing tools?
Hongmeng smart home [1.0]
A hodgepodge of ICER knowledge points (attached with a large number of topics, which are constantly being updated)
LeetCode1051(C#)
解决rosdep的报错问题
超分辨率技术在实时音视频领域的研究与实践
AI writes a poem
Nat address translation
Cadre de validation des données Apache bval réutilisé
POJ 1182: food chain (parallel search) [easy to understand]
Redis
GSAP animation library
Desci: is decentralized science the new trend of Web3.0?
[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
Tapdata 的 2.0 版 ,开源的 Live Data Platform 现已发布
2022上半年朋友圈都在传的10本书,找到了
POJ 2392 Space Elevator