LeetCode #429 N-ary Tree Level Order Traversal N叉树的层序遍历

Description:
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:


LeetCode #429 N-ary Tree Level Order Traversal N叉树的层序遍历_第1张图片
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.

题目描述:
给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。

例如,给定一个 3叉树 :


LeetCode #429 N-ary Tree Level Order Traversal N叉树的层序遍历_第2张图片
3叉树

返回其层序遍历:

[
     [1],
     [3,2,4],
     [5,6]
]

思路:
参考LeetCode #107 Binary Tree Level Order Traversal II 二叉树的层次遍历 II
时间复杂度O(n), 空间复杂度O(n)

代码:
C++:

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector children;

    Node() {}

    Node(int _val, vector _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector> levelOrder(Node* root) {
        vector> result;
        if (!root) return result;
        queue q;
        q.push(root);
        while (!q.empty()) {
            vector temp;
            int s = q.size();
            for (int i = 0; i < s; i++) {
                Node* cur = q.front();
                temp.push_back(cur -> val);
                for (int j = 0; j < cur -> children.size(); j++) q.push(cur -> children[j]);
                q.pop();
            } 
            result.push_back(temp);
        }
        return result;
    }
};

Java:

/*
// Definition for a Node.
class Node {
    public int val;
    public List children;

    public Node() {}

    public Node(int _val,List _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List> levelOrder(Node root) {
        List> result = new ArrayList<>();
        if (root == null) return result;
        Queue queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            List temp = new ArrayList<>();
            int len = queue.size();
            for (int i = 0; i < len; i++) {
                Node t = queue.poll();
                temp.add(t.val);
                for (int j = 0; j < t.children.size(); j++) queue.add(t.children.get(j));
            }
            result.add(temp);
        }
        return result;
    }
}

Python:

"""
# Definition for a Node.
class Node:
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        result = []
        def bfs(root, result, n=0):
            if root:
                try:
                    result[n].append(root.val)
                except IndexError:
                    result.append([root.val])
                for i in root.children:
                    bfs(i, result, n + 1)
        bfs(root, result)
        return result

你可能感兴趣的:(LeetCode #429 N-ary Tree Level Order Traversal N叉树的层序遍历)