Title: Sequence traversal of n-fork trees
Given an n-tree, return a sequential traversal of its node values. (that is, from left to right, layer by layer).Copy the code
Example:
For example, given a 3-fork tree:Copy the code
Return its sequence traversal: [[1], [3,2,4], [5,6]]Copy the code
Think about:
This problem is a simple N - fork tree sequence traversal algorithm.Copy the code
Implementation:
class Solution { public List<List<Integer>> levelOrder(Node root) { List<List<Integer>> list = new ArrayList<>(); if (root == null) return list; List<Node> nodes = root.children; List<Node> nodeList; List<Integer> r = new ArrayList<>(); r.add(root.val); list.add(r); while (nodes.size() > 0) { nodeList = new ArrayList<>(); r = new ArrayList<>(); for (Node temp : nodes) { nodeList.addAll(temp.children); r.add(temp.val); } list.add(r); nodes = nodeList; } return list; }}Copy the code