112. 路径总和

Problem: 112. 路径总和

思路

仍然是万能的回溯大法,因为无法使用for循环,我们只能一条一条的写:

1
2
3
4
5
6
7
8
9
10
if (node->left != nullptr) {
sum += node->left->val;
backTracing(node->left, targetSum);
sum -= node->left->val;
}
if (node->right != nullptr) {
sum += node->right->val;
backTracing(node->right, targetSum);
sum -= node->right->val;
}

注意我们的返回条件,当node为空,或node的左右子树都为空时返回,同时对比一下targitSum

1
(node->left == nullptr && node->right == nullptr)

同时,可以剪枝,当已经有结果了直接返回,if (res) return;

还要注意,由于我们第一个节点没有加入sum,我们在遍历之前要加入sum += root->val;

复杂度

时间复杂度:

添加时间复杂度, 示例: $O(n)$

空间复杂度:

添加空间复杂度, 示例: $O(n)$

Code

[]
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
38
39
40
41
42
43
44
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
int sum = 0;
bool res = false;
void backTracing(TreeNode* node, int targetSum) {
if (res)
return;
if (node == nullptr ||
(node->left == nullptr && node->right == nullptr)) {
if (sum == targetSum) {
res = true;
}
return;
}
if (node->left != nullptr) {
sum += node->left->val;
backTracing(node->left, targetSum);
sum -= node->left->val;
}
if (node->right != nullptr) {
sum += node->right->val;
backTracing(node->right, targetSum);
sum -= node->right->val;
}
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return res;
sum += root->val;
backTracing(root, targetSum);
return res;
}
};