This commit is contained in:
Sainnhe Park 2023-01-31 12:08:00 +08:00
parent 0efe4e243c
commit 63f60259ee
3 changed files with 44 additions and 0 deletions

View 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

View File

@ -159,3 +159,5 @@ vector<vector<int>> iter(Node *root) {
return result;
}
```
如果需要找某一层的什么节点的话,考虑用这个版本的层序遍历。

View 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;
}