← Home

429. N-ary Tree Level Order Traversal

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
429

Let's make this one less mysterious. For 429. N-ary Tree Level Order Traversal, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: two pointers, sliding window.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The solution is organized around the main LeetCode entry point and a few local helpers.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • 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 level order traversal of its nodes' values. (ie, from left to right, level by level).
03**/
04
05/*
06// Definition for a Node.
07class Node {
08public:
09    int val;
10    vector<Node*> children;
11
12    Node() {}
13
14    Node(int _val, vector<Node*> _children) {
15        val = _val;
16        children = _children;
17    }
18};
19*/
20
21//Runtime: 160 ms, faster than 93.75% of C++ online submissions for N-ary Tree Level Order Traversal.
22//Memory Usage: 34.3 MB, less than 6.06% of C++ online submissions for N-ary Tree Level Order Traversal.
23class Solution {
24public:
25    vector<vector<int>> levelOrder(Node* root) {
26        if(root==NULL){
27            return vector<vector<int>>();
28        }
29        
30        queue<Node*> q;
31        //root: level 0, 1 node in this level
32        int level = 0, levelCount = 1, nextLevelCount = 0;
33        vector<vector<int>> ans;
34        vector<int> levelAns;
35        
36        q.push(root);
37        
38        while(!q.empty()){
39            Node* cur = q.front();
40            q.pop();
41            for(Node* c : cur->children){
42                if(c!=NULL)q.push(c);
43            }
44            
45            nextLevelCount+=cur->children.size();
46            levelAns.push_back(cur->val);
47            
48            levelCount--;
49            if(levelCount==0){
50                //We have seen all nodes in this level
51                ans.push_back(levelAns);
52                //need a new vector
53                levelAns = vector<int>();
54                //levelCount
55                levelCount = nextLevelCount;
56                nextLevelCount = 0;
57                level++;
58            }
59        }
60        
61        return ans;
62    }
63};

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.