From 66ac5f1bf20c72b97579f86a1d5440bd658daf08 Mon Sep 17 00:00:00 2001 From: Eatswap Date: Wed, 15 Mar 2023 11:12:22 +0800 Subject: [PATCH] add: 230315 --- cpp/2303/230315.cpp | 44 +++++++++++++++++++++++++++++++++++++++++ cpp/2303/CMakeLists.txt | 2 +- 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 cpp/2303/230315.cpp diff --git a/cpp/2303/230315.cpp b/cpp/2303/230315.cpp new file mode 100644 index 0000000..b954828 --- /dev/null +++ b/cpp/2303/230315.cpp @@ -0,0 +1,44 @@ +#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) {} +}; + +/** + * 958. Check Completeness of a Binary Tree + * + * Given the root of a binary tree, determine if it is a complete binary tree. + * In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. + */ + +class Solution { +public: + static bool isCompleteTree(const TreeNode* r) { + std::queue> q; + q.emplace(1, r); + for (int c = 1; !q.empty(); ++c) { + const auto [v, p] = q.front(); + q.pop(); + if (v != c) + return false; + if (p->left) { + q.emplace(v << 1, p->left); + if (p->right) + q.emplace(v << 1 | 1, p->right); + } else if (p->right) return false; + } + return true; + } +}; + +int main() { + auto* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)), new TreeNode(3, nullptr, new TreeNode(6))); + std::cout << Solution::isCompleteTree(t); + return 0; +} diff --git a/cpp/2303/CMakeLists.txt b/cpp/2303/CMakeLists.txt index e26fea0..86d660c 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.cpp) +ADD_EXECUTABLE(2303 230315.cpp)