← Home

589. N-ary Tree Preorder Traversal

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
stackC++Markdown
589

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 589. N-ary Tree Preorder Traversal, the solution in this repository is mainly a stack solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: stack.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are preorder.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given an n-ary tree, return the preorder traversal of its nodes' values.
03
04For example, given a 3-ary tree:
05
06Return its preorder traversal as: [1,3,5,6,2,4].
07
08Note:
09
10Recursive solution is trivial, could you do it iteratively?
11**/
12
13//recursive
14//Your runtime beats 46.00 % of cpp submissions.
15/*
16// Definition for a Node.
17class Node {
18public:
19    int val;
20    vector<Node*> children;
21
22    Node() {}
23
24    Node(int _val, vector<Node*> _children) {
25        val = _val;
26        children = _children;
27    }
28};
29*/
30class Solution {
31public:
32    vector<int> ans;
33    vector<int> preorder(Node* root) {
34        if(root!=NULL){
35            ans.push_back(root->val);
36            for(Node* child : root->children){
37                preorder(child);
38            }
39        }
40        return ans;
41    }
42};
43
44//iterative
45//Your runtime beats 15.94 % of cpp submissions.
46/*
47// Definition for a Node.
48class Node {
49public:
50    int val;
51    vector<Node*> children;
52
53    Node() {}
54
55    Node(int _val, vector<Node*> _children) {
56        val = _val;
57        children = _children;
58    }
59};
60*/
61class Solution {
62public:
63    
64    vector<int> preorder(Node* root) {
65        vector<int> ans;
66        stack<Node*> stk;
67        
68        stk.push(root);
69        while(!stk.empty()){
70            Node* node = stk.top();
71            stk.pop();
72            
73            if(node!=NULL){
74                ans.push_back(node->val);
75                //put the children into stack in reverse order
76                for(vector<Node*>::reverse_iterator it=node->children.rbegin(); it!=node->children.rend();it++){
77                    stk.push(*it);
78                }
79            }
80            
81        }
82        return ans;
83    }
84};
85
86/**
87Complexity Analysis
88
89Time complexity : we visit each node exactly once, and for each visit, 
90the complexity of the operation (i.e. appending the child nodes) is proportional to the number of child nodes n (n-ary tree). 
91Therefore the overall time complexity is O(N), where N is the number of nodes, i.e. the size of tree.
92
93Space complexity : depending on the tree structure, we could keep up to the entire tree, therefore, 
94the space complexity is O(N).
95**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.