题目描述:
很明显使用的是递归来进行
我的代码:
class Solution {
public int maxDepth(Node root) {
int max = 0;
if(root == null){
return 0;
}
if(root.children.size() == 0){
return 1;
}
List<Integer> res = new ArrayList<>();
List<Node> ch = root.children;
for (Node node : ch) {
res.add(1 + getMaxDepth(node));
}
System.out.println(res.toString());
for (Integer node : res) {
max = node > max? node : max;
}
return max;
}
public int getMaxDepth(Node node){
List<Integer> res = new ArrayList<>();
if(node == null){
return 0;
}
int max = 0;
List<Node> ch = new ArrayList<>();
ch = node.children;
if(ch.size() == 0){
return 1;
}
for (Node node1 : ch) {
res.add(1 + getMaxDepth(node1));
}
for (Integer node2 : res) {
max = node2 > max? node2 : max;
}
return max;
}
}
我的那个代码有许多冗余的地方,因此可以考虑改进的。
排名靠前的代码
class Solution {
int depth=0;
public int maxDepth(Node root) {
if(root==null)
return 0;
helper(root, 0);
return depth+1;
}
public void helper(Node root, int level) {
if(root==null)
return;
if(level>depth)
depth=level;
if(root!=null && root.children!=null && root.children.size()>0) {
for(Node child : root.children) {
helper(child, level+1);
}
}
}
}