用递归
提交代码
class Solution {
public int minTime(int n, int[][] edges, List<Boolean> hasApple) {
TreeNode[] nodes=new TreeNode[n];
for(int i=0;i<n;i++)
nodes[i]=new TreeNode(i);
for(int[] e:edges) {
nodes[e[0]].next.add(nodes[e[1]]);
}
int res=0;
for(TreeNode node : nodes[0].next) {
res+=countPath(node,hasApple);
}
return res;
}
private int countPath(TreeNode root, List<Boolean> hasApple) {
int res=0;
if(root==null) return 0;
for(TreeNode node: root.next) {
res+=countPath(node, hasApple);
}
if(res==0&&hasApple.get(root.val))
return 2;
else if(res==0&&!hasApple.get(root.val))
return 0;
return res+2;
}
}
class TreeNode {
int val;
List<TreeNode> next=new ArrayList<>();
TreeNode(int x) { val = x; }
}
运行结果

本文深入探讨了递归算法的应用,通过具体的代码实例讲解了如何使用递归解决树形结构问题,如计算带有苹果标记的路径长度。代码中定义了一个解决方案类,包含用于计算最小时间的公共方法和用于计数路径的私有方法。
897

被折叠的 条评论
为什么被折叠?



