题目描述:
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
- 解法一:递归:递归遍历N叉树的孩子节点,并存入Integer类型的集合中,然后用
Conllections.max
求几个的最大值,加上根节点。
/*
// Definition for a Node.
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;
}
};
*/
class Solution {
public int maxDepth(Node root) {
if (root == null) {
return 0;
} else if (root.children.isEmpty()) {
return 1;
} else {
List<Integer> depth = new LinkedList<>();
for (Node cur : root.children) {
depth.add(maxDepth(cur));
}
return Collections.max(depth) + 1;
}
}
}
- 解法二:用C++语言,遍历N叉树,用cur表示当前的孩子节点,若当前节点大于max,更新max,最后加上根节点。
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
int maxDepth(Node* root) {
if (root == nullptr) return 0;
int max = 0, cur = 0;
for (int i = 0; i < root->children.size(); i++) {
cur = maxDepth(root->children[i]);
if (max < cur) max = cur;
}
return max + 1;
}
};
- 解法三:使用Pair将Node节点和节点的深度Integer进行配对
/*
// Definition for a Node.
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;
}
};
*/
class Solution {
public int maxDepth(Node root) {
Queue<Pair<Node, Integer>> queue = new LinkedList<>();
if (root != null) {
queue.add(new Pair(root, 1));
}
int depth = 0;
while (!queue.isEmpty()) {
Pair<Node, Integer> cur = queue.poll();
root = cur.getKey();
int curDepth = cur.getValue();
if (root != null) {
depth = Math.max(depth, curDepth);
for (Node current : root.children) {
queue.add(new Pair(current, curDepth + 1));
}
}
}
return depth;
}
}