mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update104.二叉树的最大深度,添加C#版
This commit is contained in:
@ -1022,6 +1022,61 @@ impl Solution {
|
|||||||
max_depth
|
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">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user