leetcode 437. Path Sum III
题意:求一棵二叉树中,所有一段连续路径之和等于给定值的路径数目。
思路:想了半天就只能想到暴力。。。复杂度大概O(n^2)。。。也不是不可以接受。。。但是感觉这也太暴力了。。就去看了题解。。。发现题解就还真是暴力orz。。。
1/**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10class Solution { //思路:枚举每个起点???好暴力啊。。。卧槽。。正解就是这样。。。
11public:
12 int dfs(TreeNode* root,int sum)
13 {
14 int res = 0 ;
15 if (root==NULL) return res;
16 if (root->val==sum) res++;
17 res += dfs(root->left,sum-root->val)+dfs(root->right,sum-root->val);
18 return res;
19 }
20 int pathSum(TreeNode* root, int sum) {
21 if (root==NULL) return 0;
22 return dfs(root,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
23 }
24};