LeetCode 559: Maximum Depth of N-ary Tree Solution
Master LeetCode problem 559 (Maximum Depth of N-ary Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
559. Maximum Depth of N-ary Tree
Problem Explanation
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
maxDepthto 1 (accounting for the current level). - For each child node of the root node, recursively calculate the depth and update
maxDepthwith 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.
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 559 (Maximum Depth of N-ary Tree)?
This page provides optimized solutions for LeetCode problem 559 (Maximum Depth of N-ary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 559 (Maximum Depth of N-ary Tree)?
The time complexity for LeetCode 559 (Maximum Depth of N-ary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 559 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 559 in Java, C++, or Python.