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

链接: http://leetcode.com/problems/path-sum-ii/

5/9/2017

算法班

3ms, 52%

DFS + backtracking

注意的问题:

ArrayList.removeRange(start, end)是protected的,所以第21,26行不能调用此函数并尝试不做第15行的remove。

可以把第13,19,24行的list.add()放到第12行之前来refactor

 1 public class Solution {
 2     public List<List<Integer>> pathSum(TreeNode root, int sum) {
 3         List<List<Integer>> ret = new ArrayList<>();
 4         if (root == null) return ret;
 5         ArrayList<Integer> list = new ArrayList<Integer>();
 6         pathSum(root, ret, sum, list);
 7         return ret;
 8     }
 9     
10     private void pathSum(TreeNode root, List<List<Integer>> ret, int sum, ArrayList<Integer> list) {
11         if (root == null) return;
12         if (root.left == null && root.right == null && root.val == sum) {
13             list.add(root.val);
14             ret.add(new ArrayList<Integer>(list));
15             list.remove(list.size() - 1);
16             return;
17         }
18         if (root.left != null) {
19             list.add(root.val);
20             pathSum(root.left, ret, sum - root.val, list);
21             list.remove(list.size() - 1);
22         }
23         if (root.right != null) {
24             list.add(root.val);
25             pathSum(root.right, ret, sum - root.val, list);
26             list.remove(list.size() - 1);
27         }
28         return;
29     }
30 }

有人尝试做iterative的算法:

https://discuss.leetcode.com/topic/31698/java-solution-iterative-and-recursive

也有BFS + queue

https://discuss.leetcode.com/topic/18444/python-solutions-recursively-bfs-queue-dfs-stack

更多讨论:

https://discuss.leetcode.com/category/121/path-sum-ii

posted @ 2017-05-10 11:24  panini  阅读(117)  评论(0编辑  收藏  举报