leetcode题解-112-路径总和

题目

My way

递归实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 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 {
private:
void dfs(TreeNode* root, int& pathSum, int sum, bool& res)
{
if (!root || res) return ;

pathSum += root->val;

// 到达叶子结点时
if (!root->left && !root->right && pathSum == sum) res = true;

dfs(root->left, pathSum, sum, res);
dfs(root->right, pathSum, sum, res);

pathSum -= root->val;
}

public:
bool hasPathSum(TreeNode* root, int sum)
{
int pathSum = 0;
bool res = false;

dfs(root, pathSum, sum, res);

return res;
}
};