From 06b1e482b1cbc974d0b6a57fabe051468a02f11d Mon Sep 17 00:00:00 2001 From: Eatswap Date: Thu, 20 Apr 2023 23:29:34 +0800 Subject: [PATCH] add: 230419 --- cpp/2304/230419.cpp | 58 +++++++++++++++++++++++++++++++++++++++++ cpp/2304/CMakeLists.txt | 2 +- 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 cpp/2304/230419.cpp diff --git a/cpp/2304/230419.cpp b/cpp/2304/230419.cpp new file mode 100644 index 0000000..248d6dc --- /dev/null +++ b/cpp/2304/230419.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#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) {} +}; + +/** + * 1372. Longest ZigZag Path in a Binary Tree + * + * You are given the root of a binary tree. + * + * A ZigZag path for a binary tree is defined as follow: + * + * Choose any node in the binary tree and a direction (right or left). + * If the current direction is right, move to the right child of the current node; otherwise, move to the left child. + * Change the direction from right to left or from left to right. + * Repeat the second and third steps until you can't move in the tree. + * Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). + * + * Return the longest ZigZag path contained in that tree. + */ + +class Solution { +private: + std::pair f(TreeNode* r) noexcept; + + std::unordered_map> m; + +public: + int longestZigZag(TreeNode* root) noexcept; +}; + +int Solution::longestZigZag(TreeNode* root) noexcept { + f(root); + return std::transform_reduce(m.begin(), m.end(), 0, [](int x, int y) { return std::max(x, y); }, [](auto&& x) { + return std::max(x.second.first, x.second.second); + }); +} + +std::pair Solution::f(TreeNode* r) noexcept { + if (m.count(r)) + return m[r]; + return m[r] = { + r->left ? f(r->left).second + 1 : 0, + r->right ? f(r->right).first + 1 : 0 + }; +} + +int main() { + return 0; +} diff --git a/cpp/2304/CMakeLists.txt b/cpp/2304/CMakeLists.txt index 977590a..87d3eb6 100644 --- a/cpp/2304/CMakeLists.txt +++ b/cpp/2304/CMakeLists.txt @@ -4,4 +4,4 @@ PROJECT(2304) SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_EXPORT_COMPILE_COMMANDS true) -ADD_EXECUTABLE(2304 230420-CN.cpp) +ADD_EXECUTABLE(2304 230419.cpp)