From 523d79e94a11dd2ff37d61f96ccb74d3df702e2c Mon Sep 17 00:00:00 2001 From: eat-swap Date: Fri, 13 May 2022 20:56:43 +0800 Subject: [PATCH] add: 220513 [cpp] --- cpp/2205/220513.cpp | 53 +++++++++++++++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220513.cpp diff --git a/cpp/2205/220513.cpp b/cpp/2205/220513.cpp new file mode 100644 index 0000000..185dd8a --- /dev/null +++ b/cpp/2205/220513.cpp @@ -0,0 +1,53 @@ +#include + +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + explicit Node(int _val = 0, Node* _left = nullptr, Node* _right = nullptr, Node* _next = nullptr) : val(_val), left(_left), right(_right), next(_next) {} +}; + +class Solution { +public: + static Node* connect(Node* root) { + if (!root) + return nullptr; + + Node* qNode[6144] = {root}; + int qLevel[6144] = {0}; + int front = 0, rear = 1; + + while (rear > front) { + Node* n = qNode[front]; + int level = qLevel[front]; + ++front; + + if (rear > front && level == qLevel[front]) { + n->next = qNode[front]; + } + + if (n->left) { + qNode[rear] = n->left; + qLevel[rear] = 1 + level; + ++rear; + } + + if (n->right) { + qNode[rear] = n->right; + qLevel[rear] = 1 + level; + ++rear; + } + } + + return root; + } +}; + +int main() { + auto* r = new Node(1, new Node(2, new Node(4), new Node(5)), new Node(3, nullptr, new Node(7))); + auto h = Solution::connect(r); + return 0; +} diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index b94ece2..3342587 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220512.cpp) +ADD_EXECUTABLE(2205 220513.cpp)