path-sum(路径和)

1.题目

(1)题目1:给定一棵二叉树和一个和,确定树是否有根到叶的路径,这样沿路径加起来的所有值就等于给定的和。
例如:
鉴于下面的二叉树andsum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
返回true,因为存在根到叶路径5→4→11→2,其和为22。
(2)题目2:给定一个二叉树和一个和,找到每个路径的总和等于给定总和的所有根到叶路径。
例如:
鉴于下面的二叉树andsum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
    返回:
    [
       [5,4,11,2],
       [5,8,4,5]
    ]

2.分析过程

   考察树的深度优先遍历DFS

3.代码实现

(1)代码1:

public class Solution{

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

(2)代码2:

import java.util.*;
public class Solution {
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
        ArrayList<ArrayList<Integer>> listAll=new ArrayList<>();
        if(root==null) return listAll;
        ArrayList<Integer> list=new ArrayList<>();
        int count=0;
        pathSum(root,sum,list,listAll,count);
        return listAll;
    }

    public void pathSum(TreeNode root, int sum,ArrayList<Integer> list,ArrayList<ArrayList<Integer>> listAll,int count){
        int temp=count;
        ArrayList<Integer> tempList=new ArrayList<>();
        tempList.addAll(list);
        if(root.left==null && root.right==null){
            temp+=root.val;
            if(temp==sum){
                tempList.add(root.val);
                listAll.add(tempList);
            }
        }else{
            temp+=root.val;
            tempList.add(root.val);
            if(root.left!=null) pathSum(root.left,sum,tempList,listAll,temp);
            if(root.right!=null) pathSum(root.right,sum,tempList,listAll,temp);
        }
    } 
}

题目1来自牛客网leetcode
题目2来自牛客网leetcode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值