Leetcode 559. Maximum Depth of N
You are given an N-ary tree (a tree in which nodes can have an arbitrary number of children), and you need to determine the maximum depth of the tree. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
You can assume that:
To determine the maximum depth of an N-ary tree, we can use a Depth-First Search (DFS) approach. Here are the general steps:
nullptr
, the depth is 0.The DFS approach ensures that all paths from the root to the leaf are traversed, and the longest path is identified.
Here is the C++ code for calculating the maximum depth of an N-ary tree:
#include <vector>
#include <algorithm>
// Definition for a Node.
class Node {
public:
int val;
std::vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, std::vector<Node*> _children) {
val = _val;
children = _children;
}
};
class Solution {
public:
int maxDepth(Node* root) {
if (root == nullptr) return 0;
int max_depth = 1;
for (Node* child : root->children) {
max_depth = std::max(max_depth, 1 + maxDepth(child));
}
return max_depth;
}
};
By structuring our solution this way, we ensure a clear and efficient traversal of the tree to find the maximum depth.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?