-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath_sum.cc
More file actions
64 lines (59 loc) · 1.31 KB
/
path_sum.cc
File metadata and controls
64 lines (59 loc) · 1.31 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Source: https://leetcode-cn.com/problems/path-sum
// Author: Shihao Liu
// Date: 2021-12-07
#include <queue>
#include <algorithm>
#include "cpp/definitions.h"
using namespace std;
class Solution_1 {
public:
/**
* @brief 递归, 深度优先搜索
*
* @时间复杂度 O(n)
*/
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) {
return false;
}
if (!root->left && !root->right) {
return root->val == targetSum;
} else {
return hasPathSum(root->left, targetSum - root->val)
|| hasPathSum(root->right, targetSum - root->val);
}
}
};
class Solution_2 {
public:
/**
* @brief 迭代, 广度优先搜索
*
* @时间复杂度 O(n)
*/
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) {
return false;
}
queue<pair<TreeNode *, int>> que;
que.push(make_pair(root, 0));
TreeNode *node;
int sum;
while (!que.empty()) {
node = que.front().first;
sum = que.front().second;
que.pop();
sum += node->val;
if (!node->left && !node->right && sum == targetSum) {
return true;
}
if (node->left) {
que.push(make_pair(node->left, sum));
}
if (node->right) {
que.push(make_pair(node->right, sum));
}
}
return false;
}
};