113. Path Sum II java solutions

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]
]
 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     List<List<Integer>> ans = new ArrayList<List<Integer>>();
12     public List<List<Integer>> pathSum(TreeNode root, int sum) {
13         if(root == null) return ans;
14         List<Integer> tmp = new ArrayList<Integer>();
15         recursive(root,sum,tmp);
16         return ans;
17     }
18     
19     public void recursive(TreeNode root, int sum, List<Integer> tmp){
20         if(root.val == sum && root.left == null && root.right == null){
21             tmp.add(root.val);
22             ans.add(tmp);
23             return;
24         }
25         if(root.left != null){
26             List<Integer> tmp1 = new ArrayList<Integer>(tmp);//需要使用新的list,不然原先的tmp修改会影响到right
27             tmp1.add(root.val);
28             recursive(root.left,sum-root.val,tmp1);
29         }
30         if(root.right != null){
31             List<Integer> tmp2 = new ArrayList<Integer>(tmp);
32             tmp2.add(root.val);
33             recursive(root.right,sum-root.val,tmp2);
34         }
35     }
36 }

 

posted @ 2016-07-13 14:08  Miller1991  阅读(130)  评论(0编辑  收藏  举报