Path Sum II

来源:互联网 发布:高斯滤波器的算法 编辑:程序博客网 时间:2024/06/05 02:18

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
先记录每条路径,若碰到叶子切点,且路径之和恰好等于sum,则记录该路径,递归回退时回退该路径。

public class Solution {    List<List<Integer>> treeList =  new ArrayList<List<Integer>>();    public  void pathSumRe(TreeNode root, int sum,List<Integer> list)    {        if(root == null)        {            return;        }        int value = root.val;        list.add(value);        if((root.right ==null) && (root.left == null) && (value == sum))//叶子节点        {          treeList.add(new ArrayList<Integer>(list));        }       pathSumRe(root.right, (sum - value), list) ;       pathSumRe(root.left, (sum - value), list);       list.remove(list.size() - 1);    }    public List<List<Integer>> pathSum(TreeNode root, int sum) {         List<Integer> list = new ArrayList<Integer>();        pathSumRe(root, sum,list);        return treeList;    }}
0 0