diff --git a/include/s0404_sum_of_left_leaves.hpp b/include/s0404_sum_of_left_leaves.hpp new file mode 100644 index 0000000..4dacbe5 --- /dev/null +++ b/include/s0404_sum_of_left_leaves.hpp @@ -0,0 +1,15 @@ +#ifndef S0404_sum_of_left_leaves_HPP +#define S0404_sum_of_left_leaves_HPP + +#include + +#include "structures.hpp" + +using namespace std; + +class S0404 { + public: + int sumOfLeftLeaves(TreeNode* root); +}; + +#endif diff --git a/notes/src/btree_iter.md b/notes/src/btree_iter.md index cc72bb0..2882afa 100644 --- a/notes/src/btree_iter.md +++ b/notes/src/btree_iter.md @@ -159,3 +159,5 @@ vector> iter(Node *root) { return result; } ``` + +如果需要找某一层的什么节点的话,考虑用这个版本的层序遍历。 diff --git a/src/s0404_sum_of_left_leaves.cpp b/src/s0404_sum_of_left_leaves.cpp new file mode 100644 index 0000000..f9e7f08 --- /dev/null +++ b/src/s0404_sum_of_left_leaves.cpp @@ -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 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; +}