题目描述
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:
The depth of the tree is at most 1000.
The total number of nodes is at most 5000.
方法思路
class Solution {
//Runtime: 2 ms, faster than 99.95%
//Memory Usage: 44.7 MB, less than 41.44%
public int maxDepth(Node root) {
if(root == null) return 0;
int root_depth = 0;
for(Node node : root.children){
int temp = maxDepth(node);
if(temp > root_depth)
root_depth = temp;
}
return root_depth + 1;
}
}

本文介绍了一种求解N叉树最大深度的算法,通过递归方式遍历树的每个节点,找到从根节点到最远叶节点的最长路径长度。算法实现简洁高效,时间复杂度为O(n),空间复杂度为O(h)。
470

被折叠的 条评论
为什么被折叠?



