Java implementation LeetCode 429 N-tree traversal sequence

Sequence-tree traversal 429. N

Given an N-ary tree traversal sequence returns its node value. (That is, from left to right, layer by layer traversal).

For example, given a tree 3:

Here Insert Picture Description

Returns to its traversal sequence:

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

Description:

Depth of the tree is not more than 1,000.
The total number of nodes of the tree is not more than 5,000.

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

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    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;
//     helper(root, 0, res);
//     return res;
// }

// private void helper(Node root, int depth, List<List<Integer>> res) {
//     if (root == null) return;
//     //判断是否是新的一层
//     if (depth + 1 > res.size()) {
//         res.add(new ArrayList<>());
//     }
//     res.get(depth).add(root.val);

//     //处理子节点
//     for (Node node : root.children) {
//         if (node != null) {
//             helper(node, depth + 1, res);
//         }
//     }
// }


//队列迭代

public List<List<Integer>> levelOrder(Node root) {
    List<List<Integer>> res = new ArrayList<>();
    if (root == null) return res;
    Queue<Node> queue = new LinkedList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
        int count = queue.size();
        //外层循环为一层
        List<Integer> list = new ArrayList<>();
        while (count-- > 0) {
            //将当前元素的非空子节点压入栈
            Node cur = queue.poll();
            list.add(cur.val);
            for (Node node : cur.children) {
                if (node != null) {
                    queue.add(node);
                }
            }
        }
        res.add(list);
    }
    return res;
}

 
}
Released 1539 original articles · won praise 20000 + · views 2.11 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104886804