美文网首页LeetCode
429. N-ary Tree Level Order Trav

429. N-ary Tree Level Order Trav

作者: matrxyz | 来源:发表于2020-08-07 06:32 被阅读0次

    Given an n-ary tree, return the level order traversal of its nodes' values.
    Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

    Solution:

    思路: Simple BFS

    Time Complexity: O(N) Space Complexity: O(N)

    Solution Code:

    class Solution {
        public List<List<Integer>> levelOrder(Node root) {
            
            List<List<Integer>> result = new ArrayList<>();
            if (root == null) {
                return result;
            }
            
            Queue<Node> queue = new LinkedList<>();
            queue.offer(root);
            
            while (!queue.isEmpty()) {
                List<Integer> curLevelResult = new ArrayList<>();
                
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    Node curNode = queue.poll();
                    curLevelResult.add(curNode.val);
                    for (Node child : curNode.children) {
                        queue.offer(child);
                    }
                }
                result.add(curLevelResult);
            }
            return result;
        }
    }
    

    相关文章

      网友评论

        本文标题:429. N-ary Tree Level Order Trav

        本文链接:https://www.haomeiwen.com/subject/tsmxdktx.html