From 91803365aceaef3199e367f03b3a2c4e5f8101bc Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Sun, 13 Mar 2022 14:39:36 +0800 Subject: [PATCH] add: 220312-CN [cpp] --- cpp/2203/220312-CN.cpp | 38 ++++++++++++++++++++++++++++++++++++++ cpp/2203/CMakeLists.txt | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 cpp/2203/220312-CN.cpp diff --git a/cpp/2203/220312-CN.cpp b/cpp/2203/220312-CN.cpp new file mode 100644 index 0000000..68eed91 --- /dev/null +++ b/cpp/2203/220312-CN.cpp @@ -0,0 +1,38 @@ +#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) + */ + +/** + * 590. N-ary Tree Postorder Traversal + * Given the root of an n-ary tree, return the postorder 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 postorder(Node* root) { + std::vector ret; + std::function traverse = [&](const Node* const ptr) { + if (!ptr) return; + for (const Node* const i : ptr->children) + traverse(i); + ret.push_back(ptr->val); + }; + traverse(root); + return ret; + } +}; diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index cbdae08..9701b8c 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 220313.cpp) +ADD_EXECUTABLE(2203 220312-CN.cpp)