zoukankan      html  css  js  c++  java
  • 429.N叉树的层次遍历

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

    例如,给定一个 3叉树 :

     

    返回其层序遍历:

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

    说明:

    1. 树的深度不会超过 1000
    2. 树的节点总数不会超过 5000
    class Solution {
        public List<List<Integer>> levelOrder(Node root) {
            List<List<Integer>> res = new LinkedList<>();
            if(root == null) return res;
            Queue<Node> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()) {
                List<Integer> list = new LinkedList<>();
                int sz = queue.size();
                for(int i = 0; i < sz; i++) {
                    list.add(queue.peek().val); //返回首部
                    queue.addAll(queue.poll().children); //移除首部后的子树
                }
                res.add(list);
            }
            return res;
        }
    }
  • 相关阅读:
    CodeForces
    hdu4003 树形dp
    hdu2196
    poj2486
    hdu1502 树形dp入门题
    cf 686D
    bzoj2763 分层图
    hdu4424 并查集+贪心+思维
    poj1734 最小环+输出路径
    集训题解1
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10458666.html
Copyright © 2011-2022 走看看