From a8e062f2b699398f64b1cfcacc34cca1715b2b4c Mon Sep 17 00:00:00 2001 From: Eatswap Date: Tue, 14 Mar 2023 23:58:07 +0800 Subject: [PATCH] add: 230314 --- cpp/2303/230314.cpp | 46 +++++++++++++++++++++++++++++++++++++++++ cpp/2303/CMakeLists.txt | 2 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 cpp/2303/230314.cpp diff --git a/cpp/2303/230314.cpp b/cpp/2303/230314.cpp new file mode 100644 index 0000000..37ea557 --- /dev/null +++ b/cpp/2303/230314.cpp @@ -0,0 +1,46 @@ +#include + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + + explicit TreeNode(int x, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {} +}; + +/** + * 129. Sum Root to Leaf Numbers + * + * You are given the root of a binary tree containing digits from 0 to 9 only. + * Each root-to-leaf path in the tree represents a number. + * For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. + * Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. + * A leaf node is a node with no children. + */ + +class Solution { +public: + static int sumNumbers(const TreeNode* root) { + if (!root) + return 0; + int stack[16]{root->val}, ptr = 0, ans = 0; + std::function dfs = [&](const TreeNode* r) { + if (!r->left && !r->right) { + ans += stack[ptr]; + return; + } + ++ptr; + if (r->left) { + stack[ptr] = 10 * stack[ptr - 1] + r->left->val; + dfs(r->left); + } + if (r->right) { + stack[ptr] = 10 * stack[ptr - 1] + r->right->val; + dfs(r->right); + } + --ptr; + }; + dfs(root); + return ans; + } +}; diff --git a/cpp/2303/CMakeLists.txt b/cpp/2303/CMakeLists.txt index 7234884..e26fea0 100644 --- a/cpp/2303/CMakeLists.txt +++ b/cpp/2303/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2303) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2303 230314-CN.cpp) +ADD_EXECUTABLE(2303 230314.cpp)