https://leetcode.com/problems/path-sum-iii/description/
求和为sum的树路径数量,只能从上往下,起点不一定为根
增加一个父节点S,往下遍历时用hashmap记录S到每个点的距离,以及总距离。用总距离减去目标值即为这条路径剩余量,然后在hashmap中搜索剩余量得到路径数。
class Solution { public int pathSum(TreeNode root, int sum) { Map<Integer,Integer> map = new HashMap<>(); map.put(0,1); return dfs(root,map,0,sum); } public int dfs(TreeNode root,Map<Integer,Integer> map,int distance,int sum) { if(root==null) return 0; distance += root.val; int numOfPath = map.getOrDefault(distance - sum,0); map.put(distance,map.getOrDefault(distance,0)+1); numOfPath += dfs(root.left,map,distance,sum); numOfPath += dfs(root.right,map,distance,sum); map.put(distance,map.get(distance)-1); return numOfPath; } }
其中这两句顺序是重要的,之前这里没注意就卡了很久
int numOfPath = map.getOrDefault(distance - sum,0);
map.put(distance,map.getOrDefault(distance,0)+1);