如果从根节点开始找,每次sum减掉val则到了叶子节点的时候,sum肯定等于叶子节点的值。否则,就没有这么一条路径。朴素深搜,好装逼的词!!
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null)
return false;
if(root.left==null&&root.right==null)
return sum==root.val;
return hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum-root.val);
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum){
List<List<Integer>> result = new LinkedList<List<Integer>>();
List<Integer> currentResult = new LinkedList<Integer>();
pathSum(root,sum,currentResult,result);
return result;
}
public void pathSum(TreeNode root, int sum, List<Integer> currentResult,
List<List<Integer>> result) {
if (root == null)
return;
currentResult.add(new Integer(root.val));
if (root.left == null && root.right == null && sum == root.val) {
result.add(new LinkedList(currentResult));
currentResult.remove(currentResult.size() - 1);//don't forget to remove the last integer
return;
} else {
pathSum(root.left, sum - root.val, currentResult, result);
pathSum(root.right, sum - root.val, currentResult, result);
}
currentResult.remove(currentResult.size() - 1);
}
}
对于每个节点来说,它既可以是路径开始的地方,也可以是中间点,当然,也可以是结尾的点,因此,遍历到一个节点时,需要执行三个操作:
1.以当前节点cur作为路径的开始,搜索满足sum的路径(此过程也是一个递归过程,先更新sum=sum+cur.val,然后从cur.left和cur.right分别进行搜索,更新sum=sum-cur.val);
2.以cur.left为路径的开始,搜索满足条件的路径;
3.以cur.right为路径的开始,搜索满足条件的路径;
故需要两个递归函数,一个搜索满足sum的路径,一个控制路径的起始点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
return pathSumFrom(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
private int pathSumFrom(TreeNode node, int sum) {
if (node == null) return 0;
return (node.val == sum ? 1 : 0)
+ pathSumFrom(node.left, sum - node.val) + pathSumFrom(node.right, sum - node.val);
}
}
这是倒着来,从底向上。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int pathSum(TreeNode root, int sum) {
int[] pre = new int[1000];
return pathHelper(root, sum, pre, 0);
}
private int pathHelper(TreeNode root, int sum, int[] pre, int depth) {
if (root == null) {
return 0;
}
pre[depth] = root.val;
int hit = 0;
int currVal = 0;
for (int i = depth; i >= 0; i--) {
currVal += pre[i];
if (currVal == sum) {
hit++;
}
}
hit += pathHelper(root.left, sum, pre, depth + 1) + pathHelper(root.right, sum, pre, depth + 1);
return hit;
}
}