LeetCode 559: Maximum Depth of N-ary Tree
Problem Description
Explanation:
To find the maximum depth of an N-ary tree, we can use a recursive approach. We start from the root node and recursively calculate the maximum depth of each child node. The maximum depth of the tree is the maximum of the depths of all child nodes plus 1 (to account for the current level).
Algorithm:
- If the root node is null, return 0.
- Initialize a variable
maxDepth
to 1 (accounting for the current level). - For each child node of the root node, recursively calculate the depth and update
maxDepth
with the maximum depth found. - Return
maxDepth
.
Time Complexity:
The time complexity of this algorithm is O(N), where N is the total number of nodes in the N-ary tree.
Space Complexity:
The space complexity is O(H), where H is the height of the tree.
Solutions
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
int maxDepth = 1;
for (Node child : root.children) {
maxDepth = Math.max(maxDepth, 1 + maxDepth(child));
}
return maxDepth;
}
}
Related LeetCode Problems
Loading editor...