From 500ed73d2231c058ae2c358aed689855770ce9ff Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Wed, 29 Dec 2021 17:10:10 +0800 Subject: [PATCH] add: 211229 --- 2112/211229.cpp | 75 +++++++++++++++++++++++++++++++++++++++++++++ 2112/CMakeLists.txt | 2 +- 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 2112/211229.cpp diff --git a/2112/211229.cpp b/2112/211229.cpp new file mode 100644 index 0000000..2cd4848 --- /dev/null +++ b/2112/211229.cpp @@ -0,0 +1,75 @@ +#include +#include + +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(nullptr), right(nullptr), next(nullptr) {} + + explicit Node(int _val) : val(_val), left(nullptr), right(nullptr), next(nullptr) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; + + +class Solution { +public: + static Node* connect(Node* root) { + Node* queue[1 << 12] {root}; + for (int front = 0, rear = 1; front < rear && queue[front]; ++front) { + if (!(front + 1 & front + 2)) + queue[front]->next = nullptr; + else + queue[front]->next = queue[1 + front]; + if (queue[front]->left) + queue[rear++] = queue[front]->left; + if (queue[front]->right) + queue[rear++] = queue[front]->right; + } + return root; + } +}; + +void printTree(const Node* const root) { + std::queue q; + q.push(root); + while (!q.empty()) { + const auto* const t = q.front(); + q.pop(); + printf("V->%d ", t->val); + if (t->left) { + printf("L->%d ", t->left->val); + q.push(t->left); + } + if (t->right) { + printf("R->%d ", t->right->val); + q.push(t->right); + } + if (t->next) + printf("N->%d", t->next->val); + printf("\n"); + } +} + +int main() { + Node r(1); + std::queue q; + q.push(&r); + while (!q.empty()) { + auto* const t = q.front(); + q.pop(); + if (t->val < 16) { + q.push(t->left = new Node(t->val << 1)); + q.push(t->right = new Node((t->val << 1) + 1)); + } + } + Solution::connect(&r); + printTree(&r); + return 0; +} \ No newline at end of file diff --git a/2112/CMakeLists.txt b/2112/CMakeLists.txt index 91e2cd6..9ad460a 100644 --- a/2112/CMakeLists.txt +++ b/2112/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2112) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2112 211228.cpp) \ No newline at end of file +ADD_EXECUTABLE(2112 211229.cpp) \ No newline at end of file