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

来源:互联网 发布:克伦威尔 知乎 编辑:程序博客网 时间:2024/06/13 22:38

题目

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

思路

使用递归
前序遍历,在到达叶子节点时判断是否符合要求,无论是否符合要求,都要后退一步,(即存放数值的对列移去最后一次添加的值,,然后递归返回),继续判断下一分支路径

链接:https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca来源:牛客网public class Solution {    private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>(); //listAll设置成静态变量就会有问题    private ArrayList<Integer> list = new ArrayList<Integer>();    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {        if(root == null) return listAll;        list.add(root.val);        target -= root.val;        if(target == 0 && root.left == null && root.right == null)             listAll.add(new ArrayList<Integer>(list));        FindPath(root.left, target);        FindPath(root.right, target);        list.remove(list.size()-1);        return listAll;    }}
原创粉丝点击