diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index f4c6cfc8..1f55f197 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -1033,6 +1033,9 @@ impl Solution { } ``` ### C# + +0104.二叉树的最大深度 + ```csharp // 递归法 public int MaxDepth(TreeNode root) { @@ -1088,7 +1091,76 @@ public int MaxDepth(TreeNode root) } ``` +559.n叉树的最大深度 +递归法 +```csharp + /* + 递归法 + */ + public class Solution { + public int MaxDepth(Node root) { + int res = 0; + /* 终止条件 */ + if(root == null){ + return 0; + } + + /* logic */ + // 遍历当前节点的子节点 + for (int i = 0; i < root.children.Count; i++) + { + res = Math.Max(res, MaxDepth(root.children[i])); + } + return res + 1; + } + } + // @lc code=end +``` + 迭代法(层序遍历) +```csharp + /* + 迭代法 + */ + public class Solution + { + public int MaxDepth(Node root) + { + Queue que = new Queue(); // 使用泛型队列存储节点 + + int res = 0; + + if(root != null){ + que.Enqueue(root); // 将根节点加入队列 + } + while (que.Count > 0) + { + int size = que.Count; // 获取当前层的节点数 + res++; // 深度加一 + + for (int i = 0; i < size; i++) + { + // 每一层的遍历 + + var curNode = que.Dequeue(); // 取出队列中的节点 + for (int j = 0; j < curNode.children.Count; j++) + { + if (curNode.children[j] != null) + { + que.Enqueue(curNode.children[j]); // 将子节点加入队列 + } + } + } + } + + return res; // 返回树的最大深度 + + } + } +``` + +

+