Formatted question description: https://leetcode.ca/all/559.html

559. Maximum Depth of N-ary Tree (Easy)

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:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

Solution 1. Recursive

// OJ: https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

// Time: O(N)
// Space: O(logN)
class Solution {
public:
    int maxDepth(Node* root) {
        if (!root) return 0;
        int maxd = 0;
        for (auto ch : root->children) {
            maxd = max(maxd, maxDepth(ch));
        }
        return 1 + maxd;
    }
};

Java

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public int maxDepth(Node root) {
        if (root == null)
            return 0;
        if (root.children == null || root.children.size() == 0)
            return 1;
        int maxDepth = 1;
        Queue<Node> queue = new LinkedList<Node>();
        Queue<Integer> depthQueue = new LinkedList<Integer>();
        queue.offer(root);
        depthQueue.offer(1);
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            int depth = depthQueue.poll();
            maxDepth = Math.max(maxDepth, depth);
            List<Node> children = node.children;
            if (children != null && children.size() > 0) {
                int newDepth = depth + 1;
                for (Node child : children) {
                    queue.offer(child);
                    depthQueue.offer(newDepth);
                }
            }
        }
        return maxDepth;
    }
}

All Problems

All Solutions