## LeetCode: Path Sum II 解题报告

#### 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]
]

## SOLUTION 1:

 1 /**
2  * Definition for binary tree
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     public List<List<Integer>> pathSum(TreeNode root, int sum) {
12         List<List<Integer>> ret = new ArrayList<List<Integer>>();
13
14         List<Integer> path = new ArrayList<Integer>();
15         if (root == null) {
16             return ret;
17         }
18
20         sum -= root.val;
21
22         dfs(root, sum, path, ret);
23
24         return ret;
25     }
26
27     public void dfs(TreeNode root, int sum, List<Integer> path, List<List<Integer>> ret) {
28         if (root == null) {
29             return;
30         }
31
32         if (sum == 0 && root.left == null && root.right == null) {
34             return;
35         }
36
37         if (root.left != null) {
39             dfs(root.left, sum - root.left.val, path, ret);
40             path.remove(path.size() - 1);
41         }
42
43         if (root.right != null) {
45             dfs(root.right, sum - root.right.val, path, ret);
46             path.remove(path.size() - 1);
47         }
48     }
49 }
View Code

## SOLUTION 2:

1. 当null的时候返回。

2. 当前节点是叶子 并且sum与root的值相同，则增加一个可能的解。

3. 如果没有解，将sum 减掉当前root的值，并且向左树，右树递归即可。

 1 // SOLUTION 2
2     public List<List<Integer>> pathSum(TreeNode root, int sum) {
3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
4
5         List<Integer> path = new ArrayList<Integer>();
6         if (root == null) {
7             return ret;
8         }
9
10         dfs2(root, sum, path, ret);
11
12         return ret;
13     }
14
15     public void dfs2(TreeNode root, int sum, List<Integer> path, List<List<Integer>> ret) {
16         if (root == null) {
17             return;
18         }
19
21         sum -= root.val;
22         if (sum == 0 && root.left == null && root.right == null) {
24         } else {
25             dfs2(root.left, sum, path, ret);
26             dfs2(root.right, sum, path, ret);
27         }
28
29         path.remove(path.size() - 1);
30     }
View Code

posted on 2015-03-30 09:17  Yu's Garden  阅读(623)  评论(0编辑  收藏