# C#LeetCode刷题之#559-N叉树的最大深度​​​​​​​（Maximum Depth of N-ary Tree）

## 问题

• 树的深度不会超过 1000。
• 树的节点总不会超过 5000。

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example, given a `3-ary` tree:

We should return its max depth, which is 3.

Note:

• The depth of the tree is at most `1000`.
• The total number of nodes is at most `5000`.

## 示例

```public class Program {

public static void Main(string[] args) {
var root = new Node(1,
new List<Node> {
new Node(3, new List<Node> {
new Node(5, new List<Node>()),
new Node(6, new List<Node>())
}),
new Node(2, new List<Node>()),
new Node(4, new List<Node>())
});

var res = MaxDepth(root);
Console.WriteLine(res);

res = MaxDepth2(root);
Console.WriteLine(res);

}

public static int MaxDepth(Node root) {
if(root == null) return 0;
var res = 1;
Depth(root, 1, ref res);
return res;
}

public static void Depth(Node root, int depth, ref int max) {
if(root.children == null || root.children.Count == 0) {
max = Math.Max(max, depth);
return;
}
foreach(var child in root.children) {
Depth(child, depth + 1, ref max);
}
}

public static int MaxDepth2(Node root) {
if(root == null) return 0;
var res = 0;
if(root.children != null && root.children.Count != 0) {
foreach(var child in root.children) {
var depth = MaxDepth2(child);
res = Math.Max(res, depth);
}
}
return res + 1;
}

public class Node {
public int val;
public IList<Node> children;
public Node() { }
public Node(int _val, IList<Node> _children) {
val = _val;
children = _children;
}
}

}```

```3
3```