Skip to content

Commit 29eb6f6

Browse files
committed
update 0104.二叉树的最大深度.md: Add 559.n叉树的最大深度 C#版本
1 parent 8cb21cd commit 29eb6f6

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

problems/0104.二叉树的最大深度.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1033,6 +1033,9 @@ impl Solution {
10331033
}
10341034
```
10351035
### C#
1036+
1037+
0104.二叉树的最大深度
1038+
10361039
```csharp
10371040
// 递归法
10381041
public int MaxDepth(TreeNode root) {
@@ -1088,7 +1091,76 @@ public int MaxDepth(TreeNode root)
10881091
}
10891092
```
10901093

1094+
559.n叉树的最大深度
1095+
递归法
1096+
```csharp
1097+
/*
1098+
递归法
1099+
*/
1100+
public class Solution {
1101+
public int MaxDepth(Node root) {
1102+
int res = 0;
1103+
/* 终止条件 */
1104+
if(root == null){
1105+
return 0;
1106+
}
1107+
1108+
/* logic */
1109+
// 遍历当前节点的子节点
1110+
for (int i = 0; i < root.children.Count; i++)
1111+
{
1112+
res = Math.Max(res, MaxDepth(root.children[i]));
1113+
}
1114+
return res + 1;
1115+
}
1116+
}
1117+
// @lc code=end
1118+
```
1119+
迭代法(层序遍历)
1120+
```csharp
1121+
/*
1122+
迭代法
1123+
*/
1124+
public class Solution
1125+
{
1126+
public int MaxDepth(Node root)
1127+
{
1128+
Queue<Node> que = new Queue<Node>(); // 使用泛型队列存储节点
1129+
1130+
int res = 0;
1131+
1132+
if(root != null){
1133+
que.Enqueue(root); // 将根节点加入队列
1134+
}
1135+
while (que.Count > 0)
1136+
{
1137+
int size = que.Count; // 获取当前层的节点数
1138+
res++; // 深度加一
1139+
1140+
for (int i = 0; i < size; i++)
1141+
{
1142+
// 每一层的遍历
1143+
1144+
var curNode = que.Dequeue(); // 取出队列中的节点
1145+
for (int j = 0; j < curNode.children.Count; j++)
1146+
{
1147+
if (curNode.children[j] != null)
1148+
{
1149+
que.Enqueue(curNode.children[j]); // 将子节点加入队列
1150+
}
1151+
}
1152+
}
1153+
}
1154+
1155+
return res; // 返回树的最大深度
1156+
1157+
}
1158+
}
1159+
```
1160+
1161+
10911162
<p align="center">
10921163
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
10931164
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
10941165
</a>
1166+

0 commit comments

Comments
 (0)