N-ary Tree Preorder Traversal || Recursive

·

1 min read

Problem Statement:-

Given the root of an n-ary tree, return the preorder traversal of its nodes' values.

N ary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Example 1:-narytreeexample.png Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]

Approach:-

In a Binary Tree, we first print the root data then we go for the left child followed by the right child; But in an n-ary tree instead of having two children, we have n children so we need to iterate over all the children preceded by the root’s value.

class Solution {
public:
    void preorder(Node* root, vector<int>& res)
    {
        if(root==NULL) return;
        res.push_back(root->val);
        for(int i=0;i<root->children.size();i++)
        preorder(root->children[i],res);
    }
    vector<int> preorder(Node* root) {
        vector<int> res;
        preorder(root,res);
        return res;
    }
};