Path Sum 二叉树中和为某一值的路径

Leetcode 112/113/437. Path Sum

参考:剑指offer 26:二叉树中和为某一值的路径

 

112:

Given a binary tree and a sum, determineif the tree has a root-to-leaf path such that adding up all the values alongthe 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 aroot-to-leaf path 5->4->11->2 which sumis 22.

 

这道题是为了判断二叉树中有没有从顶到叶子节点的一个路径,使得路径上的值的和为目标值。

分析:很简单,不需要记录路径,直接使用递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum){
        if(root==null){
            return false;
        }
        if(root.right==null&&root.left==null){
            return (sum==root.val);
        }
        boolean b1=(root.left!=null)?(hasPathSum(root.left,sum-root.val)):false;
        boolean b2=(root.right!=null)?(hasPathSum(root.right,sum-root.val)):false;
        return b1||b2;
    }
}


113:

Given a binary tree and a sum, find allroot-to-leaf paths where each path's sum equals the given sum.

For example:
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]

]

这个题比上个题稍微难了一些,需要给出路径了。

分析:我们可以使用一个栈来暂存路径。同样使用递归(前序遍历)来遍历二叉树。当用前序遍历的方式访问到某一节点时,我们把该节点添加到路径上。如果该节点为叶子节点并且路径中的值的和正好等于目标值,则当前路径符合要求,存到我们的res中。 如果当前节点不是叶子节点,则访问其子节点。子节点访问结束后,需要在暂存栈弹出当前节点。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        ArrayList<List<Integer>> res=new ArrayList<List<Integer>>();
        Stack<Integer> cache=new Stack<Integer>();
        if(root==null){
            return res;
        }
        respathSum(root,sum,cache,res);
        return res;
    }
    public void respathSum(TreeNode root,int sum,Stack<Integer> cache,ArrayList<List<Integer>> res){
        cache.push(root.val);
        if(root.left==null&&root.right==null&&root.val==sum){
            Stack <Integer> s=new Stack<Integer>();
            s.addAll(cache);
            res.add(s);
        }
        if(root.left!=null){
            respathSum(root.left,sum-root.val,cache,res);
        }
        if(root.right!=null){
            respathSum(root.right,sum-root.val,cache,res);
        }
        cache.pop();
    }
}


 

437

You are given a binary tree in which each node contains an integervalue.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf,but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in therange -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
 
      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1
 
Return 3. The paths that sum to 8 are:
 
1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

这个题又比上个题要难一点,路径可能不从根节点开始,也可能不在叶子节点结束。但是不需要所有路径,只需要给出可能的路径值就行了。这里同样使用递归(前序遍历),同样需要注意在处理完左右子节点之后,需要一个回到父节点状态的操作。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int pathSum(TreeNode root, int sum) {
        if(root==null){
            return 0;
        }
        ArrayList <Integer> a=new ArrayList<Integer>();
        Para p=new Para();
        p.cache=0;
        p.a=a;
        p.sum=sum;
        respathSum(root,p);
        return p.cache;
    }
    public void respathSum(TreeNode root,Para p){
        for(int i=0;i<(p.a).size();i++){
            (p.a).set(i,(p.a).get(i)+root.val);
        }
        (p.a).add(root.val);
        for(int i:(p.a)){
            if(i==p.sum){
                p.cache++;
            }
        }
        if(root.left!=null){
            respathSum(root.left,p);
        }
        if(root.right!=null){
            respathSum(root.right,p);
        }
        for(int i=0;i<(p.a).size();i++){
            (p.a).set(i,(p.a).get(i)-root.val);
        }
        (p.a).remove((p.a).size()-1);
    }
}
class Para{
    ArrayList<Integer> a;
    int cache;
    int sum;
}




 

问题描述: 给定一棵二叉树和一个整数目标值,找出所有从根节点到叶子节点的路径,使得路径上的节点值之和等于目标值。 解题思路: 我们可以使用深度优先搜索(DFS)的思想来解决这个问题。具体步骤如下: 1. 定义一个列表path,用于存储当前的路径。 2. 递归遍历每个节点: a. 将当前节点添加到path。 b. 如果当前节点是叶子节点且路径上的节点值之和等于目标值,则将当前路径添加到结果。 c. 递归遍历当前节点的左子树和右子树。 d. 在递归结束后,将当前节点从path移除,以便开始探索其他路径。 3. 返回结果列表,即所有路径和等于目标值的路径。 代码实现: ``` class Solution: def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]: def dfs(node, path, target): if not node: return path.append(node.val) if not node.left and not node.right and sum(path) == target: res.append(path.copy()) dfs(node.left, path, target) dfs(node.right, path, target) path.pop() res = [] dfs(root, [], targetSum) return res ``` 以上代码,我们定义了一个辅助函数dfs来进行递归遍历。在遍历的过程,我们使用列表path来存储当前路径,如果路径上的节点值之和等于目标值,则将当前路径添加到结果列表res。最后返回结果res。 时间复杂度分析: 假设二叉树的节点数为n,则时间复杂度为O(n),因为我们需要遍历每个节点一次。需要注意的是,在每个节点处,我们都会调用sum函数来计算当前路径的节点值之和,因此总的时间复杂度还需要考虑到sum函数的时间复杂度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值