-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.cpp
More file actions
94 lines (85 loc) · 2.45 KB
/
Copy pathPathSum.cpp
File metadata and controls
94 lines (85 loc) · 2.45 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* =====================================================================================
* Filename: PathSum.cpp
*
* Description:
*
* Version: 1.0
* Created: 2015-03-16
* Revision: none
* Compiler: gcc
*
* Author: yixun
*
* =====================================================================================
Problem: Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Hide Tags Tree Depth-first Search
解题思路:
前序遍历递归程序,算和
*/
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (root == NULL) return false;
int remain = sum - root->val;
if (remain == 0 && root->left == NULL && root->right == NULL) {
return true;
}
bool hasLeftSum = false;
if (root->left) {
hasLeftSum = hasPathSum(root->left, remain);
}
if (hasLeftSum) {
return true;
}
if (root->right) {
return hasPathSum(root->right, remain);
}
return false;
}
bool hasPathSumV2(TreeNode *root, int sum) {
if (root == NULL) return false;
vector<TreeNode*> stack;
stack.push_back(root);
vector<int> sum_stack;
sum_stack.push_back(sum);
while (!stack.empty()) {
TreeNode *node = stack.back();
stack.pop_back();
int cur_sum = sum_stack.back();
sum_stack.pop_back();
int remain = cur_sum - node->val;
if (remain == 0 && node->left == NULL && node->right == NULL) {
return true;
}
if (node->right) {
sum_stack.push_back(remain);
stack.push_back(node->right);
}
if (node->left) {
sum_stack.push_back(remain);
stack.push_back(node->left);
}
}
return false;
}
};