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:

使用递归解决,先把下一个可能要加的节点加入到path中,再使用递归依次计算即可。

 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         
19         path.add(root.val);
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) {
33             ret.add(new ArrayList<Integer>(path));
34             return;
35         }
36         
37         if (root.left != null) {
38             path.add(root.left.val);
39             dfs(root.left, sum - root.left.val, path, ret);
40             path.remove(path.size() - 1);
41         }
42         
43         if (root.right != null) {
44             path.add(root.right.val);
45             dfs(root.right, sum - root.right.val, path, ret);
46             path.remove(path.size() - 1);
47         }
48     }
49 }
View Code

相关文章:

  • 2021-07-24
  • 2021-10-07
  • 2021-08-21
  • 2022-02-11
  • 2021-06-11
  • 2021-12-20
猜你喜欢
  • 2021-12-17
  • 2022-02-10
  • 2021-06-14
  • 2021-12-05
  • 2021-10-29
  • 2021-12-15
  • 2021-07-05
相关资源
相似解决方案