image.png

解题思路

image.png

  1. class Solution {
  2. private int sum;
  3. public int pathSum(TreeNode root, int sum) {
  4. this.sum = sum;
  5. return getSum(root, new int[1000], 0);
  6. }
  7. private int getSum(TreeNode root, int[] vals, int layer) {
  8. if(root == null) return 0;
  9. vals[layer] = root.val;
  10. int cur = 0;
  11. int temp = 0;
  12. for(int i = layer; i >= 0; i--)
  13. {
  14. temp += vals[i];
  15. if(temp == this.sum) cur++;
  16. }
  17. return cur + getSum(root.left, vals, layer + 1) + getSum(root.right, vals, layer + 1);
  18. }
  19. }