力扣 | 437. 路径总和 III

437. 路径总和 III
力扣 | 437. 路径总和 III_第1张图片

mport java.util.ArrayList;
import java.util.List;

/**
 * int的取值范围:
 * -2^31 ~ 2^31-1
 * 

* -2147483648 ~ 2147483647(约等于10的9次方) *

* long long的取值范围: * -2^63 ~ (2^63-1) *

* -9223372036854775808 ~ 9223372036854775807(约等于10的18次方) */ public class Problem_437_PathSum { public int pathSum(TreeNode root, int target) { return dfs(root, new ArrayList<>(), target); } public int dfs(TreeNode node, List<Long> parentPathSumList, int targetSum) { if (node == null) return 0; int cnt = 0; List<Long> tmp = new ArrayList<>(); for (int i = 0; i < parentPathSumList.size(); i++) { long sum = parentPathSumList.get(i) + node.val; tmp.add(sum); if (sum == targetSum) cnt++; } tmp.add((long) node.val); if (node.val == targetSum) cnt++; int leftCnt = dfs(node.left, tmp, targetSum); int rightCnt = dfs(node.right, tmp, targetSum); return cnt + leftCnt + rightCnt; } }

你可能感兴趣的:(计算机基础,算法学习,编程语言,leetcode,算法,职场和发展)