You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf,but it must go downwards
(traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range
-1,000,000 to 1,000,000.
Example :
Input:root=[10,5,-3,3,2,null,11,3,-2,null,1],sum=8
Output:3
Explanation:
The paths that sum to 8 are:
1.5 -> 3
2.5 -> 2 -> 1
3.-3 -> 11
题目大意:找出路径和等于给定数值的总数.注意:路径不需要从根节点开始,也不需要以叶子节点结束,而且路径的方向是朝下的.
解题思路:
利用双递归遍历
方法二:
哈希+递归
package pathsumIII;
import java.util.HashMap;
import java.util.Map;
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(){}
TreeNode(int val){this.val=val;}
TreeNode(int val,TreeNode left,TreeNode right){
this.val=val;
this.left=left;
this.right=right;
}
}
public class Solution {
/**
* 双重递归
* @param root
* @param sum
* @return
*/
public int pathSum(TreeNode root,int sum){
if(root==null){
return 0;
}
//System.out.println(root.val);
int count=travel(root,sum);
count+=pathSum(root.left,sum);
count+=pathSum(root.right,sum);
return count;
}
private int travel(TreeNode root,int sum){
int count=0;
if(root==null){
return 0;
}
if(sum==root.val){
count++;
}
count+=travel(root.left,sum-root.val);
count+=travel(root.right,sum-root.val);
return count;
}
/**
* 哈希+递归
* @param root
* @param sum
* @return
*/
public int pathSum1(TreeNode root,int sum){
Map<Integer,Integer> hashMap=new HashMap<Integer,Integer>();
hashMap.put(0,1);//对应于某个节点刚好等于sum
return recursionPathSum(root,hashMap,sum,0);
}
private int recursionPathSum(TreeNode root,Map<Integer,Integer> hashMap,int sum,int curSum){
if(root==null){
return 0;
}
int count=0;
curSum+=root.val;//当前路径和
count+=hashMap.getOrDefault(curSum-sum,0);//getOrDefault若不存在,则返回defaultValue
hashMap.put(curSum,hashMap.getOrDefault(curSum,0)+1);
count+=recursionPathSum(root.left,hashMap,sum,curSum);
count+=recursionPathSum(root.right,hashMap,sum,curSum);
hashMap.put(curSum,hashMap.get(curSum)-1);
return count;
}
public static void main(String[] args){
TreeNode root=new TreeNode(10);
TreeNode n1=new TreeNode(5);
TreeNode n2=new TreeNode(-3);
TreeNode n3=new TreeNode(3);
TreeNode n4=new TreeNode(2);
TreeNode n5=new TreeNode(11);
TreeNode n6=new TreeNode(3);
TreeNode n7=new TreeNode(-2);
TreeNode n8=new TreeNode(1);
root.left=n1;root.right=n2;
n1.left=n3;n1.right=n4;
n2.right=n5;
n3.left=n6;n3.right=n7;
n4.right=n8;
System.out.println(new Solution().pathSum(root,8));
System.out.println(new Solution().pathSum1(root,8));
}
}