给定二叉树和一个常数sum,求二叉树中路径和等于sum的所有路径个数,这些路径可以是任意起点和终点,但必须是按照从父节点到子节点的路径
方法一:强遍历,对所有节点,以该节点为起点,遍历其所有子节点,求路径和等于sum的个数,时间复杂度O(n^2)。
public int pathSum(TreeNode root, int sum) {
if(root == null)
return 0;
int num = 0;
num += countPath(root, sum);
num += pathSum(root.left, sum);
num += pathSum(root.right, sum);
return num;
}
public int countPath(TreeNode root, int sum){
if(root == null)
return 0;
int num = 0;
if(root.val == sum) num ++;
num += countPath(root.left, sum - root.val);
num += countPath(root.right, sum - root.val);
return num;
}
方法二:使用hashMap,存储根节点到达所有父节点的路径和及其个数,时间复杂度为O(n)。
计算从根节点到当前节点的和currSum,如果preSum中存在元素等于currSum - target,假设从根节点到其祖先节点k的路径和等于currSum - target,那么从k节点的子节点到当前节点的路径和就是target。例如下面的二叉树,假设当前节点为3,target = 8,那么preSum中会存储所有祖先节点与根节点的距离和个数:<10,1>, <15,1>。此时,currSum = 18,preSum中存在10 = currSum - target,因此从10的子节点5到当前节点3的路径和就刚好是8。preSum的value记录了这样的距离的个数,因此,到达3这个节点路径和为8的只有一个节点。
public int pathSum(TreeNode root, int sum) {
HashMap<Integer, Integer> preSum = new HashMap();
preSum.put(0,1);
return helper(root, 0, sum, preSum);
}
public int helper(TreeNode root, int currSum, int target, HashMap<Integer, Integer> preSum) {
if (root == null) {
return 0;
}
currSum += root.val;
int res = preSum.getOrDefault(currSum - target, 0);
preSum.put(currSum, preSum.getOrDefault(currSum, 0) + 1);
res += helper(root.left, currSum, target, preSum) + helper(root.right, currSum, target, preSum);
preSum.put(currSum, preSum.get(currSum) - 1); //注意在返回时,要把preSum中到达当前节点的路径和的个数减一
return res;
}
方法三:递归的时候,考虑从当前节点起始,或者继承祖先节点的和(实际上时间复杂度比第一种方法还大)
public class Solution {
int target;
Set<TreeNode> visited;
public int pathSum(TreeNode root, int sum) {
target = sum;
visited = new HashSet<TreeNode>(); // to store the nodes that have already tried to start path by themselves.
return pathSumHelper(root, sum, false);
}
public int pathSumHelper(TreeNode root, int sum, boolean hasParent) {
if(root == null) return 0;
//the hasParent flag is used to handle the case when parent path sum is 0.
//in this case we still want to explore the current node.
if(sum == target && visited.contains(root) && !hasParent) return 0; //当前节点作为起始节点的情况已经计算过了
if(sum == target && !hasParent) visited.add(root); //记录以当前节点为起始的情况,避免后面再多次计数
int count = (root.val == sum)?1:0;
count += pathSumHelper(root.left, sum - root.val, true); //继承祖先的和的情况
count += pathSumHelper(root.right, sum - root.val, true);
count += pathSumHelper(root.left, target , false); //以当前节点为起始的情况
count += pathSumHelper(root.right, target, false);
return count;
}