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

在这里插入图片描述

解析:

这题是个二叉树问题,需要从上到下遍历每个节点,所以可以采用前序遍历,先可以写个框架出来
public void help(TreeNode root,int target) {
        path.add(root.val);
        
        
        if(root.left != null) {
            help(root.left, target);
        }
        
        if(root.right != null) {
            help(root.right, target);
        }
        
        path.remove(path.size() - 1);
    }
这个就是前序遍历的框架,然后在想,我要把满足条件的节点放进集合,什么时候才可以把该路径的节点放进集合,满足一下条件即可
//左右节点为空,且最后一个节点刚还满足剩下的值
if(root.left == null && root.right == null && root.val == target) {
            res.add(new ArrayList<>(path));
}
然后向左右递归,递归完后,会返回上一个节点,这个时候需要把该节点从集合删除,尝试其他的情况
import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    
    ArrayList<ArrayList<Integer>> res = new ArrayList<>();
    
    ArrayList<Integer> path = new ArrayList<>();

    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root == null) {
            return res;
        }
        help(root, target);
        return res;
    }
    
    public void help(TreeNode root,int target) {
        path.add(root.val);
        if(root.left == null && root.right == null && root.val == target) {
            res.add(new ArrayList<>(path));
        }
        
        if(root.left != null) {
            help(root.left, target - root.val);
        }
        
        if(root.right != null) {
            help(root.right, target - root.val);
        }
        
        path.remove(path.size() - 1);
    }
    
    

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值