Given an N-ary tree, whose nodes return value sequence traversal . (That is, from left to right, layer by layer traversal).
For example, given a 3叉树
:
Returns to its traversal sequence:
[ [1], [3,2,4], [5,6] ]
Description:
- Does not exceed the depth of the tree
1000
. - Does not exceed the total number of nodes in the tree
5000
.
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val,List<Node> _children) { val = _val; children = _children; } }; */ class Solution { public List<List<Integer>> levelOrder(Node root) { List<List<Integer>> list = new LinkedList<>(); if(root==null) return list; Queue<Node> queue = new LinkedList<>(); queue.offer(root); int first = 1; int second = 0; List<Integer> temp = new LinkedList<>(); while(!queue.isEmpty()){ Node node = queue.poll(); first--; temp.add(node.val); Iterator<Node> iterator = node.children.iterator(); while(iterator.hasNext()){ Node cur = iterator.next(); queue.offer(cur); second++; } if(first==0){ list.add(temp); first = second; second = 0; temp = new LinkedList<>(); } } return list; } }