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

来源:互联网 发布:太原知达常青藤好进吗 编辑:程序博客网 时间:2024/04/30 13:12

题目描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
输入如图所示的一颗树,目标值为22,则输出【10,12】和【10,5,7】
这里写图片描述

思路:前序遍历整棵树,当路径上节点的和等于目标值时,将这条路径保存,然后继续遍历,直到节点为空返回。

public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {        if(root==null){            return null;        }        ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();        find(list,new ArrayList<Integer>(),root,target,0);        return list;    }    public void find(ArrayList<ArrayList<Integer>> resultList,ArrayList<Integer> list,TreeNode root,int target,int value){        if(root==null){            return;        }        list.add(root.val);        value+=root.val;        if(target==value){            resultList.add(new ArrayList<Integer>(list));        }        find(resultList,list,root.left,target,value);        find(resultList,list,root.right,target,value);        list.remove(new Integer(root.val));    }
0 0
原创粉丝点击