Update111.二叉树的最小深度,添加C#版

This commit is contained in:
eeee0717
2023-11-17 19:33:16 +08:00
parent 3ffca338ca
commit cfc78c3c57

View File

@ -708,6 +708,49 @@ impl Solution {
}
}
```
### C#
```C#
// 递归
public int MinDepth(TreeNode root)
{
if (root == null) return 0;
int left = MinDepth(root.left);
int right = MinDepth(root.right);
if (root.left == null && root.right != null)
return 1+right;
else if(root.left!=null && root.right == null)
return 1+left;
int res = 1 + Math.Min(left, right);
return res;
}
```
```C#
// 迭代
public int MinDepth(TreeNode root)
{
if (root == null) return 0;
int depth = 0;
var que = new Queue<TreeNode>();
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);
if (node.left == null && node.right == null)
return depth;
}
}
return depth;
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">