zoukankan      html  css  js  c++  java
  • 剑指offer 60. 把二叉树打印成多行

    60. 把二叉树打印成多行

    题目描述

    从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

    层序遍历即可

     1 import java.util.Queue;
     2 import java.util.LinkedList;
     3 public class Solution {
     4     ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
     5         ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
     6         if(pRoot == null){
     7             return list;
     8         }
     9         // 层序遍历
    10         Queue<TreeNode> queue = new LinkedList<TreeNode>();
    11         queue.offer(pRoot);
    12         TreeNode top;
    13         while(!queue.isEmpty()){
    14             int count = queue.size();
    15             ArrayList<Integer> innerList = new ArrayList<Integer>();
    16             for(int i = 0; i < count; i++){
    17                 top = queue.poll();
    18                 innerList.add(top.val);
    19                 if(top.left != null)
    20                     queue.offer(top.left);
    21                 if(top.right != null)
    22                     queue.offer(top.right);
    23             }
    24             list.add(innerList);
    25         }
    26         return list;
    27     }
    28     
    29 }

     注意:

    虽然使用下面的语法也能转化成int[]数组,但是效率会比我们手动使用循环来转换低很多

    int[] arr = list.stream().mapToInt(Integer::valueOf).toArray();    // 虽然也能转换成int数组,但是效率低了很多
  • 相关阅读:
    Linux 文件权限
    Linux 查看磁盘使用情况
    绑定到外部验证服务LDAP、配置 autofs
    创建逻辑卷
    查找一个字符串
    查找用户目录下的指定文件
    配置NTP时间服务器
    通过Roslyn构建自己的C#脚本(更新版)(转)
    Elon Musk
    可能改变世界的13个“终结”(上)
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/12444900.html
Copyright © 2011-2022 走看看