leetcode 112/113( Path Sum (II)路径求和)

本文探讨了二叉树的路径求和问题,通过深度优先搜索(DFS)算法,解决给定二叉树和目标和的情况下,寻找从根到叶子节点的路径,其上节点值之和等于目标和。提供了两种解决方案,一种判断是否存在这样的路径,另一种找出所有满足条件的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Note: A leaf is a node with no children.

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.

思路:
DFS,可以用中序遍历,逐个减去访问的节点值,比较时可以用sum-root.val的方式逐个减掉元素,最后只剩下当前节点值=当前sum即可

    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) {
            return false;
        }
        
        if(root.left == null && root.right == null && root.val == sum) {
            return true;
        }
        
        return(hasPathSum(root.left, sum - root.val) || 
               hasPathSum(root.right, sum - root.val));
    }

和112类似,只是这次要输出所有满足条件的path
Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
[5,4,11,2],
[5,8,4,5]
]

思路:
仍然采用112的逐个用sum-访问节点值的方法,只是这次要访问所有path,不能用112的return left || right, 而是都要访问,然后需要用一个Stack保存访问节点的值,访问完它的左右子树后pop掉这个值

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Stack<Integer> stack = new Stack<>();
        
        dfs(root, sum, stack, result);
        return result;
    }
    
    public void dfs(TreeNode root, int sum, Stack<Integer> stack, 
                   List<List<Integer>> result) {
        if(root == null) {
            return;
        }
        
        stack.push(root.val);
        
        if(root.left == null && root.right == null && root.val == sum) {
            ArrayList<Integer> tmp = new ArrayList<Integer>(stack);
            result.add(tmp);
            stack.pop();
            return;
        }
        
        dfs(root.left, sum - root.val, stack, result);
        dfs(root.right, sum - root.val, stack, result);
        
        stack.pop();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值