문제 링크: https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
이번엔 Binary Tree가 아닌 N-ary Tree의 maximum depth를 구하는 문제이다.
특이한 점은 트리의 각 노드가 아래와 같이 정의되어 있다는 것이다.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
}
N-ary Tree이기 때문에, 트리의 각 node는 left
와 right
포인터를 가지는 것이 아닌 자식 노드들의 list를 가진다.
직관적인 방법이다.
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
}
if (root.children.isEmpty()) {
return 1;
}
List<Integer> heights = new LinkedList<>();
for (Node child : root.children) {
heights.add(maxDepth(child));
}
return Collections.max(heights) + 1;
}
}
Maximum Depth of Binary Tree 풀이와 같은 방법으로 Queue를 사용해 maximum depth를 구했다.
class Solution {
Queue<Node> queue = new LinkedList<>();
public int maxDepth(Node root) {
if(root == null) return 0;
int depth = 0;
queue.offer(root);
while(!queue.isEmpty()) {
int queueSize = queue.size();
while(queueSize-- > 0) {
Node currNode = queue.poll();
List<Node> children = currNode.children;
if(children.size() != 0) putChildrenNodeToQueue(children);
}
depth++;
}
return depth;
}
void putChildrenNodeToQueue(List<Node> children) {
for(Node child : children) {
queue.offer(child);
}
}
}
모든 노드를 방문하니 시간 복잡도는 O(N)이 된다.