Update104.二叉树的最大深度,添加C#版

This commit is contained in:
eeee0717
2023-11-16 09:12:06 +08:00
parent b51573efa6
commit 3ffca338ca

View File

@ -1022,6 +1022,61 @@ impl Solution {
max_depth
}
```
### C#
```C#
// 递归法
public int MaxDepth(TreeNode root) {
if(root == null) return 0;
int leftDepth = MaxDepth(root.left);
int rightDepth = MaxDepth(root.right);
return 1 + Math.Max(leftDepth, rightDepth);
}
```
```C#
// 前序遍历
int result = 0;
public int MaxDepth(TreeNode root)
{
if (root == null) return result;
GetDepth(root, 1);
return result;
}
public void GetDepth(TreeNode root, int depth)
{
result = depth > result ? depth : result;
if (root.left == null && root.right == null) return;
if (root.left != null)
GetDepth(root.left, depth + 1);
if (root.right != null)
GetDepth(root.right, depth + 1);
return;
}
```
```C#
// 迭代法
public int MaxDepth(TreeNode root)
{
int depth = 0;
Queue<TreeNode> que = new();
if (root == null) return depth;
que.Enqueue(root);
while (que.Count != 0)
{
int size = que.Count;
depth++;
for (int i = 0; i < size; i++)
{
var node = que.Dequeue();
if (node.left != null) que.Enqueue(node.left);
if (node.right != null) que.Enqueue(node.right);
}
}
return depth;
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">