Home Leetcode 589 N-ary Tree Preorder Traversal
Post
Cancel

Leetcode 589 N-ary Tree Preorder Traversal

N-ary Tree Preorder Traversal problem results

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)

Result

First Blood

Visit each node’s children recursively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{
    /*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

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

Double Kill

The code could be simpler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{

class Solution {
public:
    void pre(Node* head, vector<int>* op)
    {
        if(head)
        {
            op->push_back(head->val);
            for(int i = 0; i < head->children.size(); i++)
            {
                pre(head->children[i],op);
            }
        }
    }
    
    vector<int> preorder(Node* root) {
        vector<int> op;
        
        if(root)
        {
            pre(root,&op);
        }
       
        
        return op;
    }
};
}
This post is licensed under CC BY 4.0 by the author.
Trending Tags