From 7c3f9ba87e8c5d9a21ef9b1a4b6f639c7602af8b Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 23 Jul 2022 13:10:25 +0200 Subject: [PATCH] problems: add n-ary tree level-order traversal Signed-off-by: Matej Focko --- problems/n-ary-tree-level-order-traversal.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 problems/n-ary-tree-level-order-traversal.cpp diff --git a/problems/n-ary-tree-level-order-traversal.cpp b/problems/n-ary-tree-level-order-traversal.cpp new file mode 100644 index 0000000..68d870e --- /dev/null +++ b/problems/n-ary-tree-level-order-traversal.cpp @@ -0,0 +1,47 @@ +/* +// 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 levelOrder(vector>& traversal, Node* root, int level) + { + if (root == nullptr) { + return; + } + + if (level >= traversal.size()) { + traversal.push_back({}); + } + traversal[level].push_back(root->val); + + for (auto child : root->children) { + levelOrder(traversal, child, level + 1); + } + } + +public: + vector> levelOrder(Node* root) + { + vector> result; + levelOrder(result, root, 0); + return result; + } +};