zoukankan      html  css  js  c++  java
  • N 叉树的层序遍历

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

    例如,给定一个 3叉树 :

    返回其层序遍历:

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

    说明:

    1. 树的深度不会超过 1000
    2. 树的节点总数不会超过 5000
    /*
    // 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>> list = new LinkedList<>();
            if(root==null) return list;
            Queue<Node> queue = new LinkedList<>();
            queue.offer(root);
            int first = 1;
            int second = 0;
            List<Integer> temp = new LinkedList<>();
            while(!queue.isEmpty()){
                Node node = queue.poll();
                first--;
                temp.add(node.val);
                Iterator<Node> iterator = node.children.iterator();
                while(iterator.hasNext()){
                    Node cur = iterator.next();
                    queue.offer(cur);
                    second++;
                }
                if(first==0){
                    list.add(temp);
                    first = second;
                    second = 0;
                    temp = new LinkedList<>();
                }
            }
            return list;
        }
    }
  • 相关阅读:
    筛选法求素数
    C/C++经典面试题目
    操作系统笔试面试基本内容
    Win32/MFC的基本概念
    STL采用的标准模板库
    数据结构基本概念
    SQL基础语句
    C/C++基础概念
    计算机网络基础概念
    流水作业 批作业调度
  • 原文地址:https://www.cnblogs.com/czsy/p/10994617.html
Copyright © 2011-2022 走看看