559. Maximum Depth of N-ary Tree
Question
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.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example 1:

Input: root = [1,null,3,2,4,null,5,6]
Output: 3
Example 2:

Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: 5
Constraints:
- The total number of nodes is in the range
[0, 104]. - The depth of the n-ary tree is less than or equal to
1000.
Approach 1: BFS
Intuition
- Tracking depth in BFS is easier and straight forward.
Algorithm
- Declare and initialize a
depthvariable with1to track the max depth. (1 as if root exists the depth is at least 1) - Declare a
queue<pair<Node*, int>>to track the depth for each node. - Push the root and depth into the queue
- Loop till queue is not empty
- Get the current node and current depth from the front of the queue
- Pop the queue
- Update the max depth by comparing with the current depth
- Loop over the neighbors (children) of the current node
- Push them into the queue with currDepth + 1
- Return depth.
Code
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
};
*/
class Solution {
public:
int maxDepth(Node* root) {
if (root == NULL) return 0;
int depth = 1;
// node, depth
queue<pair<Node*, int>> q;
q.push({root, 1});
while (!q.empty()) {
Node* node = q.front().first;
int currDepth = q.front().second;
q.pop();
depth = max(currDepth, depth);
for (auto neighbor: node->children) {
q.push({neighbor, currDepth + 1});
}
}
return depth;
}
};
Complexity Analysis
- Time Complexity:
- Space Complexity:
Approach 2: DFS
Intuition
- Traversal option
Algorithm
- Declare a function
getMaxDepththat takes a node and currDepth as argument and returns an int (which is the max depth); - We can skip the base case because the tree is going to finish as some point.
- In the processing & recurse case step we are calling the same function for the children of the node.
- Calculating the maxDepth by getting the max of the function output of the child and the currentDepth
- Return the maxDepth
Code
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
};
*/
class Solution {
public:
int getMaxDepth(Node* node, int currDepth) {
int maxDepth = currDepth;
for (Node* child : node->children) {
maxDepth = max(best, getMaxDepth(child, currDepth + 1));
}
return maxDepth;
}
int maxDepth(Node* root) {
if (root == NULL) return 0;
return getMaxDepth(root, 1);
}
};
Complexity Analysis
- Time Complexity:
- Space Complexity: