当前位置:网站首页>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;
}
}
边栏推荐
- [fan Tan] after the arrival of Web3.0, where should testers go? (ten predictions and suggestions)
- Blue Bridge Cup final XOR conversion 100 points
- 自定义View必备知识,Android研发岗必问30+道高级面试题
- Read PG in data warehouse in one article_ stat
- 【Seaborn】组合图表:FacetGrid、JointGrid、PairGrid
- [Fantan] how to design a test platform?
- LeetCode刷题day49
- [source code interpretation] | source code interpretation of livelistenerbus
- 麒麟信安云平台全新升级!
- Solidity 开发环境搭建
猜你喜欢
随机推荐
Process from creation to encapsulation of custom controls in QT to toolbar (I): creation of custom controls
【饭谈】那些看似为公司着想,实际却很自私的故事 (一:造轮子)
Sator推出Web3游戏“Satorspace” ,并上线Huobi
智慧物流平台:让海外仓更聪明
redis主从、哨兵主备切换搭建一步一步图解实现
赋能智慧电力建设 | 麒麟信安高可用集群管理系统,保障用户关键业务连续性
skimage学习(2)——RGB转灰度、RGB 转 HSV、直方图匹配
Flask搭建api服务-生成API文档
[Seaborn] combination chart: pairplot and jointplot
【饭谈】如何设计好一款测试平台?
Is AI more fair than people in the distribution of wealth? Research on multiplayer game from deepmind
Blue Bridge Cup final XOR conversion 100 points
[Fantan] how to design a test platform?
First in China! Todesk integrates RTC technology into remote desktop, with clearer image quality and smoother operation
鲲鹏开发者峰会2022 | 麒麟信安携手鲲鹏共筑计算产业新生态
How to add aplayer music player in blog
Flash build API Service - generate API documents
麒麟信安中标国网新一代调度项目!
DevOps 的运营和商业利益指南
MySQL usage notes 1