> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/04-06-2022-559.-maximum-depth-of-n-ary-tree.md).

# 04/06/2022 559. Maximum Depth of N-ary Tree

559\. Maximum Depth of N-ary Tree

　method 1:

　　recursion. depth = 1 + Math.max(depth, maxDepth(each child). Noted depth should be set to 0 instead of Integer.MIN\_VALUE.

Time O(n)

Space O(h)

```
// Some code
class Solution {
    public int maxDepth(Node root) {
        if (root == null) return 0;
        int depth = 0; // cannot be MIN_VALUE
        for (Node child: root.children){
            depth = Math.max(depth, maxDepth(child));
        }
        return 1 + depth;
    }
}
```

Method 2:

use BFS to traverse each level of the tree and increment depth.

Time O(N)

Space O(N)

```
// Some code
class Solution {
    public int maxDepth(Node root) {
        if (root == null) return 0;
        Queue<Node> queue = new LinkedList<>();
         queue.offer(root);
        int depth = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            depth++;
            for (int i = 0; i < size; i++){
                Node curr = queue.poll();
                for (Node child: curr.children){
                    queue.offer(child);
                }
            }
        }
        return depth;
    }
```
