深度优先搜索
/**
* 时间复杂度 O(n)
* 空间复杂度 O(logn)
*/class Solution {
public int maxDepth(Node root) {
if (root == null){
return 0;
}
int max = 0;
for (Node c : root.children){
max = Math.max(maxDepth(c), max);
}
return max + 1;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(logn)
*/
广度优先搜索
class Solution {
public int maxDepth(Node root) {
if (root == null){
return 0;
}
Queue<Node> queue = new LinkedList<>();
int max = 0;
queue.add(root);
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++) {
Node temp = queue.poll();
for (Node c : temp.children){
queue.add(c);
}
}
max++;
}
return max;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。