Given an n-ary tree, return the level order traversal of its nodes' values.
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [[1],[3,2,4],[5,6]]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.List;import java.util.Queue;public class NAryTreeLevelorderTra {public static void main(String[] args) {// 3 node childList<Node> node3Child = new ArrayList<Node>();node3Child.add(new Node(5));node3Child.add(new Node(6));// 1 node childList<Node> node1Child = new ArrayList<Node>();node1Child.add(new Node(3, node3Child));node1Child.add(new Node(2));node1Child.add(new Node(4));// root nodeNode node = new Node(1, node1Child);List<List<Integer>> list = levelOrder(node);System.out.println(Arrays.asList(list));}public static List<List<Integer>> levelOrder(Node root) {List<List<Integer>> result = new ArrayList<>();if (root == null)return result;Queue<Node> q = new LinkedList<>();q.add(root);while (!q.isEmpty()) {int size = q.size();List<Integer> r = new ArrayList<>();while (size > 0) {root = q.poll();r.add(root.val);if (root.children != null) {for (Node child : root.children) {q.add(child);}}size--;}result.add(r);}return result;}}class Node {public int val;public List<Node> children;public Node() {}public Node(int _val) {val = _val;}public Node(int _val, List<Node> _children) {val = _val;children = _children;}}
C++
#include <bits/stdc++.h>using namespace std;struct Node{int val;vector<Node*> children;Node() {}Node(int _val){val = _val;}Node(int _val, vector<Node*> _children){val = _val;children = _children;}};//function to find level order//traversal of n ary treevector<vector<int>> levelOrder(Node* root) {vector<vector<int>> res;if(root==NULL)return res;queue<Node*>q;q.push(root);while(!q.empty()){int len=q.size();vector<int> x;for(int i=0;i<len;i++){Node *temp=q.front();q.pop();x.push_back(temp->val);for(auto child:temp->children)q.push(child);}res.push_back(x);}return res;}int main(){// 3 node childvector<Node*> node3Child;node3Child.push_back(new Node(5));node3Child.push_back(new Node(6));// 1 node childvector<Node*> node1Child;node1Child.push_back(new Node(3, node3Child));node1Child.push_back(new Node(2));node1Child.push_back(new Node(4));// root nodeNode *node = new Node(1, node1Child);vector<vector<int>> result=levelOrder(node);cout<<"[";for(int i=0;i<result.size();i++){cout<<"[";for(int j=0;j<result[i].size();j++){if(j!=result[i].size()-1)cout<<result[i][j]<<",";elsecout<<result[i][j];}cout<<"]";if(i!=result.size()-1)cout<<", ";}cout<<"]";return 0;}
No comments:
Post a Comment