Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3ffca33

Browse files
committed
Update104.二叉树的最大深度,添加C#版
1 parent b51573e commit 3ffca33

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

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

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1022,6 +1022,61 @@ impl Solution {
10221022
max_depth
10231023
}
10241024
```
1025+
### C#
1026+
```C#
1027+
// 递归法
1028+
public int MaxDepth(TreeNode root) {
1029+
if(root == null) return 0;
1030+
1031+
int leftDepth = MaxDepth(root.left);
1032+
int rightDepth = MaxDepth(root.right);
1033+
1034+
return 1 + Math.Max(leftDepth, rightDepth);
1035+
}
1036+
```
1037+
```C#
1038+
// 前序遍历
1039+
int result = 0;
1040+
public int MaxDepth(TreeNode root)
1041+
{
1042+
if (root == null) return result;
1043+
GetDepth(root, 1);
1044+
return result;
1045+
}
1046+
public void GetDepth(TreeNode root, int depth)
1047+
{
1048+
result = depth > result ? depth : result;
1049+
if (root.left == null && root.right == null) return;
1050+
1051+
if (root.left != null)
1052+
GetDepth(root.left, depth + 1);
1053+
if (root.right != null)
1054+
GetDepth(root.right, depth + 1);
1055+
return;
1056+
}
1057+
```
1058+
```C#
1059+
// 迭代法
1060+
public int MaxDepth(TreeNode root)
1061+
{
1062+
int depth = 0;
1063+
Queue<TreeNode> que = new();
1064+
if (root == null) return depth;
1065+
que.Enqueue(root);
1066+
while (que.Count != 0)
1067+
{
1068+
int size = que.Count;
1069+
depth++;
1070+
for (int i = 0; i < size; i++)
1071+
{
1072+
var node = que.Dequeue();
1073+
if (node.left != null) que.Enqueue(node.left);
1074+
if (node.right != null) que.Enqueue(node.right);
1075+
}
1076+
}
1077+
return depth;
1078+
}
1079+
```
10251080

10261081
<p align="center">
10271082
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /