From 692c3ba5371a9a616a457265931bf9d87e7ddf2a Mon Sep 17 00:00:00 2001 From: Eatswap Date: Sun, 19 Feb 2023 22:27:12 +0800 Subject: [PATCH] add: 230219 --- cpp/2302/230219.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ cpp/CMakeLists.txt | 2 +- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 cpp/2302/230219.cpp diff --git a/cpp/2302/230219.cpp b/cpp/2302/230219.cpp new file mode 100644 index 0000000..c15ec62 --- /dev/null +++ b/cpp/2302/230219.cpp @@ -0,0 +1,45 @@ +#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) {} +}; + +/** + * 103. Binary Tree Zigzag Level Order Traversal + * + * Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). + */ + +class Solution { +public: + static std::vector> zigzagLevelOrder(const TreeNode* root) { + if (!root) + return {}; + std::vector> ret {{}}; + std::queue> q; + q.emplace(root, 0); + for (int n = 0; !q.empty(); ) { + const auto [ptr, lv] = q.front(); + q.pop(); + if (lv > n) { + ret.emplace_back(); + ++n; + } + ret.back().push_back(ptr->val); + if (ptr->left) + q.emplace(ptr->left, 1 + lv); + if (ptr->right) + q.emplace(ptr->right, 1 + lv); + } + for (int i = 1; i < ret.size(); i += 2) + std::reverse(ret[i].begin(), ret[i].end()); + return ret; + } +}; diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 9dbc513..a1b133b 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -16,7 +16,7 @@ ENDIF() # Optimisation # SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Ofast -march=native -mtune=native -finline-functions -ffast-math -fomit-frame-pointer") -ADD_EXECUTABLE(leetcode-cpp main.cpp 2302/230218.cpp 2302/230218-CN.cpp 2302/230219-CN.cpp) +ADD_EXECUTABLE(leetcode-cpp main.cpp 2302/230218.cpp 2302/230218-CN.cpp 2302/230219-CN.cpp 2302/230219.cpp) # ADD_SUBDIRECTORY(2112) # ADD_SUBDIRECTORY(2201)