s0404
This commit is contained in:
parent
0efe4e243c
commit
63f60259ee
15
include/s0404_sum_of_left_leaves.hpp
Normal file
15
include/s0404_sum_of_left_leaves.hpp
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
#ifndef S0404_sum_of_left_leaves_HPP
|
||||||
|
#define S0404_sum_of_left_leaves_HPP
|
||||||
|
|
||||||
|
#include <queue>
|
||||||
|
|
||||||
|
#include "structures.hpp"
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
class S0404 {
|
||||||
|
public:
|
||||||
|
int sumOfLeftLeaves(TreeNode* root);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
@ -159,3 +159,5 @@ vector<vector<int>> iter(Node *root) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
如果需要找某一层的什么节点的话,考虑用这个版本的层序遍历。
|
||||||
|
27
src/s0404_sum_of_left_leaves.cpp
Normal file
27
src/s0404_sum_of_left_leaves.cpp
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
#include "s0404_sum_of_left_leaves.hpp"
|
||||||
|
|
||||||
|
struct TreeNodeState_S0404 {
|
||||||
|
TreeNode* ptr;
|
||||||
|
int sum;
|
||||||
|
bool isLeft;
|
||||||
|
};
|
||||||
|
|
||||||
|
int S0404::sumOfLeftLeaves(TreeNode* root) {
|
||||||
|
int sum{0};
|
||||||
|
queue<TreeNodeState_S0404> q;
|
||||||
|
if (root) q.push(TreeNodeState_S0404{root, root->val, false});
|
||||||
|
while (!q.empty()) {
|
||||||
|
TreeNodeState_S0404 front = q.front();
|
||||||
|
q.pop();
|
||||||
|
if (front.ptr->left == nullptr && front.ptr->right == nullptr &&
|
||||||
|
front.isLeft)
|
||||||
|
sum += front.ptr->val;
|
||||||
|
if (front.ptr->left)
|
||||||
|
q.push(TreeNodeState_S0404{front.ptr->left, front.sum + front.ptr->left->val,
|
||||||
|
true});
|
||||||
|
if (front.ptr->right)
|
||||||
|
q.push(TreeNodeState_S0404{front.ptr->right, front.sum + front.ptr->right->val,
|
||||||
|
false});
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user