【力扣 005】437. 路径总和 III
方法一:48 ms
1 /* 2 sumUp递归子程序求解以root为根节点的子节点之和为sum的路径数目; 3 pathSum递归部分是把根节点逐一考察,如以root->left,以root->right为根等等, 4 用sumUp求解其对应的路径数目。最终结果是全部求和,也就是pathSum return的形式。 5 */ 6 class Solution { 7 public: 8 int pathSum(TreeNode* root, int sum) 9 { 10 if(!root) return 0; 11 return sumUp(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum); 12 } 13 private: 14 int sumUp(TreeNode* root, int pre, int& sum) 15 { 16 if(!root) return 0; 17 int current = pre + root->val; 18 return (current == sum) + sumUp(root->left, current, sum) + sumUp(root->right, current, sum); 19 } 20 }