From 9ff0adaf361e34ddb2ef3ef7ba41080d338a0543 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Thu, 10 Mar 2022 01:21:51 +0800 Subject: [PATCH] add: 220310-CN [cpp] --- cpp/2203/220310-CN.cpp | 32 ++++++++++++++++++++++++++++++++ cpp/2203/CMakeLists.txt | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 cpp/2203/220310-CN.cpp diff --git a/cpp/2203/220310-CN.cpp b/cpp/2203/220310-CN.cpp new file mode 100644 index 0000000..42214f9 --- /dev/null +++ b/cpp/2203/220310-CN.cpp @@ -0,0 +1,32 @@ +#include +#include + +// Definition for a Node. +class Node { +public: + int val; + std::vector children; + + Node(int _val, std::vector _children) : val(_val), children(std::move(_children)) {} +}; + +/** + * 589. N-ary Tree Preorder Traversal + * Given the root of an n-ary tree, return the preorder traversal of its nodes' values. + * Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) + */ + +class Solution { +public: + static std::vector preorder(Node* root) { + std::vector ret; + std::function traverse = [&](const Node* const ptr) { + if (!ptr) return; + ret.push_back(ptr->val); + for (const Node* const i : ptr->children) + traverse(i); + }; + traverse(root); + return ret; + } +}; diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index a38ec52..7dd0413 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220309.cpp) +ADD_EXECUTABLE(2203 220310-CN.cpp)