剑指offer 47. 二叉树中和为某一值的路径-java

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

原题链接

输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。

从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

保证树中结点值均不小于 0。

数据范围
树中结点的数量 [0,1000]。

代码案例:在这里插入图片描述

题解

一个典型的dfs算法题

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List <List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> findPath(TreeNode root, int sum) {
        List<Integer> tmp = new ArrayList<>();
         dfs(root,sum,tmp);
         return res ;
    }
    public void dfs(TreeNode root,int sum , List<Integer> tmp){
        if(root == null) return ;
        tmp.add(root.val);
        sum -= root.val ;
        if(root.left == null  && root.right == null && sum == 0){
            res.add(new ArrayList<>(tmp));//如果不是new 一个的话结果为空
        }
        dfs(root.left,sum,tmp);
        dfs(root.right,sum,tmp);
        //要恢复现场
        tmp.remove(tmp.size()-1);//这个语句是清空ArrayList的所有 
       
    }
}
posted @   依嘫  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示