My code:
import java.util.ArrayList;
import java.util.List;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null)
return result;
hasPathSum(root, 0, sum, new ArrayList<Integer>(), result);
return result;
}
private void hasPathSum(TreeNode root, int sum, int totalSum, ArrayList<Integer> path,
ArrayList<List<Integer>> result) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null) {
if (sum + root.val == totalSum)
result.add(new ArrayList<Integer>(path));
path.remove(path.size() - 1);
return;
}
else {
hasPathSum(root.left, sum + root.val, totalSum, path, result);
hasPathSum(root.right, sum + root.val, totalSum, path, result);
path.remove(path.size() - 1);
}
}
}
My test result:
这道题目没有什么难度。
感觉还是用到了以前permutation系列题的思想,把已经用完的了结点删除。便于下一次深度遍历。DFS
**
总结, Tree DFS
**
Anyway, Good luck, Richardo!
My code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (root == null) {
return ret;
}
List<Integer> group = new ArrayList<Integer>();
helper(root, 0, sum, ret, group);
return ret;
}
private void helper(TreeNode root, int curr, int sum, List<List<Integer>> ret, List<Integer> group) {
if (root.left == null && root.right == null) {
if (root.val + curr == sum) {
group.add(root.val);
ret.add(new ArrayList<Integer>(group));
group.remove(group.size() - 1);
}
else {
return;
}
}
else {
group.add(root.val);
if (root.left != null) {
helper(root.left, root.val + curr, sum, ret, group);
}
if (root.right != null) {
helper(root.right, root.val + curr, sum, ret, group);
}
group.remove(group.size() - 1);
}
}
}
注意力没集中,没想到这道题目做了这么久。真他妈了隔壁的。。
其实就是 permutation的思想。只是形式稍微变一下。
Anyway, Good luck, Richardo! -- 08/28/2016