diff --git a/problems/n-ary-tree-preorder-traversal.cpp b/problems/n-ary-tree-preorder-traversal.cpp new file mode 100644 index 0000000..ee66ae8 --- /dev/null +++ b/problems/n-ary-tree-preorder-traversal.cpp @@ -0,0 +1,43 @@ +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() { } + + Node(int _val) + { + val = _val; + } + + Node(int _val, vector _children) + { + val = _val; + children = _children; + } +}; +*/ + +class Solution { + void preorder(vector& traversal, Node* root) + { + if (root == nullptr) { + return; + } + + traversal.push_back(root->val); + for (auto child : root->children) { + preorder(traversal, child); + } + } + +public: + vector preorder(Node* root) + { + vector result; + preorder(result, root); + return result; + } +};