429. N-ary Tree Level Order Traversal - Easy
Posted fatttcat
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了429. N-ary Tree Level Order Traversal - Easy相关的知识,希望对你有一定的参考价值。
Given an n-ary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).
For example, given a 3-ary
tree:
We should return its level order traversal:
[ [1], [3,2,4], [5,6] ]
Note:
- The depth of the tree is at most
1000
. - The total number of nodes is at most
5000
.
M1: BFS
time: O(n), space: O(N) -- N: 最多一层的节点数
/* // 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>> res = new ArrayList<>(); Queue<Node> q = new LinkedList<>(); if(root == null) { return res; } q.offer(root); while(!q.isEmpty()) { List<Integer> level = new ArrayList<>(); int size = q.size(); for(int i = 0; i < size; i++) { Node tmp = q.poll(); level.add(tmp.val); if(tmp.children != null) { for(Node n : tmp.children) { q.offer(n); } } } res.add(level); } return res; } }
M2: recursion
time: O(n), space: O(height)
/* // 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>> res = new ArrayList<>(); if(root == null) { return res; } levelOrder(root, 0, res); return res; } public void levelOrder(Node root, int level, List<List<Integer>> res) { if(root == null) { return; } if(res.size() == level) { res.add(new ArrayList<>()); } res.get(level).add(root.val); if(root.children != null) { for(Node n : root.children) { levelOrder(n, level + 1, res); } } } }
以上是关于429. N-ary Tree Level Order Traversal - Easy的主要内容,如果未能解决你的问题,请参考以下文章
429. N-ary Tree Level Order Traversal
429. N-ary Tree Level Order Traversal
429. N-ary Tree Level Order Traversal
429. N-ary Tree Level Order Traversal - Easy