标签:bin code style roo solution pre public mil sum
题意:统计路径和等于sum的路径数量。
(1)节点值可正可负
(2)路径两端不一定是根结点或叶子结点
(3)路径一定是向下
分析:路径起点
(1)位于root(统计以root开头的和等于sum的路径数量)
(2)位于root->left子树(递归)
(3)位于root->right子树(递归)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int PathRoot(TreeNode* root, int sum){ if(root == NULL) return 0; int ans = 0; if(root -> val == sum) ++ans; ans += PathRoot(root -> left, sum - root -> val) + PathRoot(root -> right, sum - root -> val); return ans; } int pathSum(TreeNode* root, int sum) { if(root == NULL) return 0; return pathSum(root -> left, sum) + pathSum(root -> right, sum) + PathRoot(root, sum); } };
LeetCode 437. Path Sum III(统计路径和等于sum的路径数量)
标签:bin code style roo solution pre public mil sum
原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12392968.html