From 96559bcf3e770a928e42ec4fee859fdc7fd61e6d Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Sun, 15 May 2022 10:16:01 +0800 Subject: [PATCH] add: 220515 [cpp] --- cpp/2205/220515.cpp | 34 ++++++++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220515.cpp diff --git a/cpp/2205/220515.cpp b/cpp/2205/220515.cpp new file mode 100644 index 0000000..392f167 --- /dev/null +++ b/cpp/2205/220515.cpp @@ -0,0 +1,34 @@ +#include +#include + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + + explicit TreeNode(int x = 0, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(x), left(l), right(r) {} +}; + +/** + * 1302. Deepest Leaves Sum + * Given the root of a binary tree, return the sum of values of its deepest leaves. + */ + +class Solution { +public: + static int deepestLeavesSum(TreeNode* r) { + if (!r) return 0; + std::queue> q; + int ret = 0, l = 0; + q.push({r, 0}); + while (!q.empty()) { + const auto [n, d] = q.front(); + q.pop(); + ret = (d == l ? ret : 0) + n->val; + l = d; + if (n->left) q.push({n->left, 1 + d}); + if (n->right) q.push({n->right, 1 + d}); + } + return ret; + } +}; diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index bae3437..e314c85 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220514.cpp) +ADD_EXECUTABLE(2205 220515.cpp)