【leetcode】1443. Minimum Time to Collect All Apples in a Tree

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

用递归

提交代码
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; }
}
运行结果

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值