437. Path Sum III

每个节点都要找有多少个 dfs对每个点找

 

 

 1 class Solution {
 2     int count = 0;
 3     int res = 0;
 4     public int pathSum(TreeNode root, int sum) {
 5         if(root == null) return 0;
 6         res = helper(root, sum, 0) + pathSum(root.left, sum) + pathSum(root.right, sum);
 7         return res;
 8         
 9     }
10     
11     public int helper(TreeNode root, int sum, int preSum){
12         if(root == null) return 0;
13         int n = 0;
14         if(preSum + root.val == sum){
15             n++;
16         }
17         n += helper(root.left, sum, preSum + root.val) + helper(root.right, sum, preSum + root.val);
18         return n;
19         
20     }
21 }

 

posted @ 2018-10-31 09:59  jasoncool1  阅读(106)  评论(0编辑  收藏  举报