LeetCode OJ 113. Path Sum II

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为某一值的从根节点到叶子节点的路径,这个题目要求把所有这样的路径找出来。如果我们要用递归的方法,如何来存储这样的路径呢?

一个节点如果有左右两个子节点,那么就会产生两条不同的路径,在递归的过程中,我们要不断地new一个list来存储新出现的分支,并要把从根节点到达当前节点的路径拷贝到新建的list中。当到达叶子节点后,如果是一条匹配路径,则把该路径加入到存储路径的list中,否则的话舍弃该路径。代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     
12     public List<List<Integer>> list = new ArrayList();
13     public List<List<Integer>> pathSum(TreeNode root, int sum) {
14         if(root == null) return list;
15         
16         List<Integer> llist = new ArrayList();
17         path(root, sum, llist);
18         return list;
19     }
20     
21     public void path(TreeNode root, int sum, List<Integer> llist){
22         if(root.left==null && root.right==null){
23             if(root.val==sum){
24                 llist.add(sum);
25                 list.add(llist);
26             }
27             return;
28         }
29         if(root.right!=null){
30             List<Integer> rlist = new ArrayList();
31             for(Integer i : llist){
32                 rlist.add(i);
33             }
34             rlist.add(root.val);
35             path(root.right, sum - root.val, rlist);
36         }
37         if(root.left!=null){
38             llist.add(root.val);
39             path(root.left, sum - root.val, llist);
40         }
41     }
42 }

 

posted @ 2016-05-03 16:07  Black_Knight  阅读(213)  评论(0编辑  收藏  举报