From 63f60259ee2a051e67fc727474e85de279ba2386 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 31 Jan 2023 12:08:00 +0800 Subject: [PATCH] s0404 --- include/s0404_sum_of_left_leaves.hpp | 15 +++++++++++++++ notes/src/btree_iter.md | 2 ++ src/s0404_sum_of_left_leaves.cpp | 27 +++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 include/s0404_sum_of_left_leaves.hpp create mode 100644 src/s0404_sum_of_left_leaves.cpp 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; +}