算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 N叉树的最大深度,我们先来看题面:
https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/
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).
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
示例
解题
遍历每一颗子树即可
class Solution {
public int maxDepth(Node root) {
if(root == null) return 0;
int max = 1;
int dep = 0;
Iterator<Node> iterator = root.children.iterator();
while(iterator.hasNext()){
dep = maxDepth(iterator.next())+1;
max = max > dep ? max : dep;
dep = 0;
}
return max;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: