/*// Definition for a Node.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; }};*/classSolution{publicList<List<Integer>>levelOrder(Noderoot){List<List<Integer>>ans=newArrayList<>();if(root==null){returnans;}Deque<Node>q=newArrayDeque<>();q.offer(root);while(!q.isEmpty()){List<Integer>t=newArrayList<>();for(intn=q.size();n>0;--n){root=q.poll();t.add(root.val);q.addAll(root.children);}ans.add(t);}returnans;}}
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funclevelOrder(root*Node)(ans[][]int){ifroot==nil{return}q:=[]*Node{root}forlen(q)>0{vart[]intforn:=len(q);n>0;n--{root=q[0]q=q[1:]t=append(t,root.Val)for_,child:=rangeroot.Children{q=append(q,child)}}ans=append(ans,t)}return}
/*// Definition for a Node.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; }};*/classSolution{privateList<List<Integer>>ans=newArrayList<>();publicList<List<Integer>>levelOrder(Noderoot){dfs(root,0);returnans;}privatevoiddfs(Noderoot,inti){if(root==null){return;}if(ans.size()<=i){ans.add(newArrayList<>());}ans.get(i++).add(root.val);for(Nodechild:root.children){dfs(child,i);}}}
/*// 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; }};*/classSolution{public:vector<vector<int>>levelOrder(Node*root){vector<vector<int>>ans;function<void(Node*,inti)>dfs=[&](Node*root,inti){if(!root){return;}if(ans.size()<=i){ans.push_back({});}ans[i++].push_back(root->val);for(auto&child:root->children){dfs(child,i);}};dfs(root,0);returnans;}};
1 2 3 4 5 6 7 8 910111213141516171819202122232425
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funclevelOrder(root*Node)(ans[][]int){vardfsfunc(root*Node,iint)dfs=func(root*Node,iint){ifroot==nil{return}iflen(ans)<=i{ans=append(ans,[]int{})}ans[i]=append(ans[i],root.Val)for_,child:=rangeroot.Children{dfs(child,i+1)}}dfs(root,0)return}