mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
update 0104.二叉树的最大深度.md: Add 559.n叉树的最大深度 C#版本
This commit is contained in:
@ -1033,6 +1033,9 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
### C#
|
### C#
|
||||||
|
|
||||||
|
0104.二叉树的最大深度
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
// 递归法
|
// 递归法
|
||||||
public int MaxDepth(TreeNode root) {
|
public int MaxDepth(TreeNode root) {
|
||||||
@ -1088,7 +1091,76 @@ public int MaxDepth(TreeNode root)
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
559.n叉树的最大深度
|
||||||
|
递归法
|
||||||
|
```csharp
|
||||||
|
/*
|
||||||
|
递归法
|
||||||
|
*/
|
||||||
|
public class Solution {
|
||||||
|
public int MaxDepth(Node root) {
|
||||||
|
int res = 0;
|
||||||
|
/* 终止条件 */
|
||||||
|
if(root == null){
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* logic */
|
||||||
|
// 遍历当前节点的子节点
|
||||||
|
for (int i = 0; i < root.children.Count; i++)
|
||||||
|
{
|
||||||
|
res = Math.Max(res, MaxDepth(root.children[i]));
|
||||||
|
}
|
||||||
|
return res + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// @lc code=end
|
||||||
|
```
|
||||||
|
迭代法(层序遍历)
|
||||||
|
```csharp
|
||||||
|
/*
|
||||||
|
迭代法
|
||||||
|
*/
|
||||||
|
public class Solution
|
||||||
|
{
|
||||||
|
public int MaxDepth(Node root)
|
||||||
|
{
|
||||||
|
Queue<Node> que = new Queue<Node>(); // 使用泛型队列存储节点
|
||||||
|
|
||||||
|
int res = 0;
|
||||||
|
|
||||||
|
if(root != null){
|
||||||
|
que.Enqueue(root); // 将根节点加入队列
|
||||||
|
}
|
||||||
|
while (que.Count > 0)
|
||||||
|
{
|
||||||
|
int size = que.Count; // 获取当前层的节点数
|
||||||
|
res++; // 深度加一
|
||||||
|
|
||||||
|
for (int i = 0; i < size; i++)
|
||||||
|
{
|
||||||
|
// 每一层的遍历
|
||||||
|
|
||||||
|
var curNode = que.Dequeue(); // 取出队列中的节点
|
||||||
|
for (int j = 0; j < curNode.children.Count; j++)
|
||||||
|
{
|
||||||
|
if (curNode.children[j] != null)
|
||||||
|
{
|
||||||
|
que.Enqueue(curNode.children[j]); // 将子节点加入队列
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res; // 返回树的最大深度
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user