437 路径总和-02
前缀和,dfs,回溯
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
int count=0;
Map<TreeNode,Integer> map=new HashMap<>();
public int pathSum(TreeNode root, int targetSum) {
dfs(root,targetSum,0);
return count;
}
public void dfs(TreeNode root,int targetSum,int currSum){
if (root==null){
return;
}
currSum+=root.val;
for (Map.Entry<TreeNode,Integer> entry:map.entrySet()){
if (currSum-entry.getValue()==targetSum){
count++;
}
}
if(currSum==targetSum){
count++;
}
map.put(root,currSum);
dfs(root.left,targetSum,currSum);
dfs(root.right,targetSum,currSum);
map.remove(root);
}
}
时间复杂度
O
(
n
)
O(n)
O(n),
n
n
n是二叉树的节点个数。
空间复杂度
O
(
h
)
O(h)
O(h),
h
h
h是二叉树的深度,使用哈希表。