当前位置:网站首页>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;
}
}
边栏推荐
- QML初学
- Seaborn数据可视化
- 智慧物流平台:让海外仓更聪明
- LeetCode 1654. The minimum number of jumps to get home one question per day
- The server is completely broken and cannot be repaired. How to use backup to restore it into a virtual machine without damage?
- MRS离线数据分析:通过Flink作业处理OBS数据
- SlashData开发者工具榜首等你而定!!!
- Proxmox VE重装后,如何无损挂载原有的数据盘?
- MySQL implements the query of merging two fields into one field
- 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?
猜你喜欢
随机推荐
Flask搭建api服务-SQL配置文件
LeetCode 213. 打家劫舍 II 每日一题
A tour of grpc:03 - proto serialization / deserialization
[Huang ah code] Why do I suggest you choose go instead of PHP?
Lex & yacc of Pisa proxy SQL parsing
Master this promotion path and share interview materials
LeetCode 1031. Maximum sum of two non overlapping subarrays
LeetCode 1043. 分隔数组以得到最大和 每日一题
[fan Tan] after the arrival of Web3.0, where should testers go? (ten predictions and suggestions)
MySQL implements the query of merging two fields into one field
First in China! Todesk integrates RTC technology into remote desktop, with clearer image quality and smoother operation
From Devops to mlops: how do it tools evolve to AI tools?
【Seaborn】组合图表:PairPlot和JointPlot
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?
Leetcode brush questions day49
Lowcode: four ways to help transportation companies enhance supply chain management
LeetCode 403. Frog crossing the river daily
Skimage learning (3) -- adapt the gray filter to RGB images, separate colors by immunohistochemical staining, and filter the maximum value of the region
Sator a lancé le jeu web 3 "satorspace" et a lancé huobi
麒麟信安中标国网新一代调度项目!