Header Ad

Leetcode N-ary Tree Level Order Traversal problem solution

In this Leetcode N-ary Tree Level Order Traversal problem solution we have given an n-ary tree, returns the level order 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.

Leetcode N-ary Tree Level Order Traversal problem solution


Problem solution in Python.

class Solution(object):
    def levelOrder(self, root):
        if not root:return []
        res = []
        stack = [root]
        while stack:
            temp = []
            next_stack = []
            for node in stack:
                temp.append(node.val)
                for child in node.children:
                    next_stack.append(child)
            stack = next_stack
            res.append(temp)
        return res



Problem solution in Java.

class Solution {
public List<List> levelOrder(Node root) {

    Queue <Node> q1=new LinkedList();
    Queue  <Node> q2=new LinkedList();
    List<List<Integer>> list=new LinkedList<List<Integer>>();
    if(root==null){
        return list;
    }
    List<Integer> list1=new ArrayList<>();
    q1.add(root);
    while(q1.size()!=0){
        Node a =q1.remove();
         // System.out.print(a.val+" ");
        list1.add(a.val);
        for(Node child:a.children){
            q2.add(child);
        }
        if(q1.size()==0){
            q1=q2;
            q2=new LinkedList();
            list.add(list1);
            list1=new ArrayList<>();
            // System.out.println();
        }
        
        
    }
    return list;
}
}


Problem solution in C++.

class Solution {
public:
    
    vector<vector<int>> levelOrder(Node* root) 
    {
        vector<vector<int>> ret;
        if(root == nullptr) return ret;
        
        queue<Node*> s;
        queue<int> num;
        
        s.push(root);
        num.push(1);
        
        while(!s.empty()) {
            
            int N = num.front();
            num.pop();
            
            int Nnext = 0;
            ret.push_back(vector<int>());
            
            for(int n=0; n<N; ++n) {
                Node *node = s.front();
                s.pop();
                Nnext += node->children.size();
                ret.back().push_back(node->val);
                for(int k=0; k<node->children.size(); ++k) s.push(node->children[k]);
            }
            
            num.push(Nnext);
        }
        
        return ret;
        
    }
};


Post a Comment

0 Comments