@@ -123,9 +123,9 @@ return false;
123
123
整体代码如下:
124
124
125
125
``` cpp
126
- class solution {
126
+ class Solution {
127
127
private:
128
- bool traversal(treenode * cur, int count) {
128
+ bool traversal(TreeNode * cur, int count) {
129
129
if (!cur->left && !cur->right && count == 0) return true; // 遇到叶子节点,并且计数为0
130
130
if (!cur->left && !cur->right) return false; // 遇到叶子节点直接返回
131
131
@@ -143,8 +143,8 @@ private:
143
143
}
144
144
145
145
public:
146
- bool haspathsum(treenode * root, int sum) {
147
- if (root == null ) return false;
146
+ bool hasPathSum(TreeNode * root, int sum) {
147
+ if (root == NULL ) return false;
148
148
return traversal(root, sum - root->val);
149
149
}
150
150
};
@@ -155,7 +155,7 @@ public:
155
155
``` cpp
156
156
class solution {
157
157
public:
158
- bool haspathsum(treenode * root, int sum) {
158
+ bool hasPathSum(TreeNode * root, int sum) {
159
159
if (root == null) return false;
160
160
if (!root->left && !root->right && sum == root->val) {
161
161
return true;
@@ -176,7 +176,7 @@ public:
176
176
177
177
c++就我们用pair结构来存放这个栈里的元素。
178
178
179
- 定义为:`pair<treenode *, int>` pair<节点指针,路径数值>
179
+ 定义为:`pair<TreeNode *, int>` pair<节点指针,路径数值>
180
180
181
181
这个为栈里的一个元素。
182
182
@@ -186,25 +186,25 @@ c++就我们用pair结构来存放这个栈里的元素。
186
186
class solution {
187
187
188
188
public:
189
- bool haspathsum(treenode * root, int sum) {
189
+ bool haspathsum(TreeNode * root, int sum) {
190
190
if (root == null) return false;
191
191
// 此时栈里要放的是pair<节点指针,路径数值>
192
- stack<pair<treenode *, int>> st;
193
- st.push(pair<treenode *, int>(root, root->val));
192
+ stack<pair<TreeNode *, int>> st;
193
+ st.push(pair<TreeNode *, int>(root, root->val));
194
194
while (!st.empty()) {
195
- pair<treenode *, int> node = st.top();
195
+ pair<TreeNode *, int> node = st.top();
196
196
st.pop();
197
197
// 如果该节点是叶子节点了,同时该节点的路径数值等于sum,那么就返回true
198
198
if (!node.first->left && !node.first->right && sum == node.second) return true;
199
199
200
200
// 右节点,压进去一个节点的时候,将该节点的路径数值也记录下来
201
201
if (node.first->right) {
202
- st.push(pair<treenode *, int>(node.first->right, node.second + node.first->right->val));
202
+ st.push(pair<TreeNode *, int>(node.first->right, node.second + node.first->right->val));
203
203
}
204
204
205
205
// 左节点,压进去一个节点的时候,将该节点的路径数值也记录下来
206
206
if (node.first->left) {
207
- st.push(pair<treenode *, int>(node.first->left, node.second + node.first->left->val));
207
+ st.push(pair<TreeNode *, int>(node.first->left, node.second + node.first->left->val));
208
208
}
209
209
}
210
210
return false;
0 commit comments