Path Sum (Java)

25 篇文章 0 订阅
21 篇文章 0 订阅
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.


For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

深搜到叶子的和判断与sum是否相等


Source

    public boolean hasPathSum(TreeNode root, int sum) {
        if( root == null){
        	return false;
        }
        if( root.left == null && root.right == null){
        	return sum - root.val == 0;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);		//递归应当注意的就是状态转移的这个式子,这道题是当前sum确定倒推到叶子所以用减 (通常是叶子确定 推到根用加)
    }

Test

 public static void main(String[] args){
    	TreeNode a = new TreeNode(5);
    	a.left = new TreeNode(4);
    	a.right = new TreeNode(8);
    	a.left.left = new TreeNode(11);
    	a.left.left.left = new TreeNode(7);
    	a.left.left.right = new TreeNode(2);
    	a.right.left = new TreeNode(13);
    	a.right.right = new TreeNode(4);
    	a.right.right.right = new TreeNode(1);
    	System.out.println(new Solution().hasPathSum(a, 22));
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回溯法是一种求解问题的算法,它通过尝试所有可能的解来找到问题的最优解。sum it up是一个求解数列中所有可能的子集和的问题,可以使用回溯法来解决。 具体实现时,可以使用递归函数来实现回溯法。首先定义一个数组来存储数列中的元素,然后定义一个递归函数,该函数接受三个参数:当前处理的元素下标、当前已经选择的元素和、目标和。在递归函数中,首先判断当前已经选择的元素和是否等于目标和,如果是,则输出当前选择的元素和,否则继续选择下一个元素进行递归。在递归过程中,需要注意剪枝,即当当前已经选择的元素和已经大于目标和时,就可以停止继续选择元素进行递归。 最后,在主函数中调用递归函数,从第一个元素开始进行递归,得到所有可能的子集和。 具体实现细节可以参考以下代码: public class SumItUp { static int[] nums; static int n; static int target; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); nums = new int[n]; for (int i = ; i < n; i++) { nums[i] = sc.nextInt(); } target = sc.nextInt(); Arrays.sort(nums); dfs(, new ArrayList<Integer>(), ); } public static void dfs(int index, List<Integer> path, int sum) { if (sum == target) { for (int i = ; i < path.size(); i++) { System.out.print(path.get(i) + " "); } System.out.println(); return; } if (sum > target || index == n) { return; } dfs(index + 1, path, sum); path.add(nums[index]); dfs(index + 1, path, sum + nums[index]); path.remove(path.size() - 1); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值