zoukankan      html  css  js  c++  java
  • 剑指Offer:二叉树打印成多行【23】

     剑指Offer:二叉树打印成多行【23】

    题目描述

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

    题目分析 

      

    Java题解

    package tree;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class PrintByLevel {
        public static void main(String[] args) {
            TreeNode t1 = new TreeNode(1);
            TreeNode t2 = new TreeNode(2);
            TreeNode t3 = new TreeNode(3);
            TreeNode t4 = new TreeNode(4);
            TreeNode t5 = new TreeNode(5);
            t1.left=t2;
            t1.right=t3;
            t2.left=t4;
            t2.right=t5;
        }
        static ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
            ArrayList<ArrayList<Integer>> re = new ArrayList<>();
            if (pRoot==null)
                return re;
    
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(pRoot);
            int nextLevel =0;
            int toBePrinted = 1;
            ArrayList<Integer> cuLevel = new ArrayList<>();
    
            while (!queue.isEmpty())
            {
                TreeNode tmp = queue.poll();
                cuLevel.add(tmp.val);
                if(tmp.left!=null)
                {
                    queue.add(tmp.left);
                    nextLevel++;
                }
                if(tmp.right!=null)
                {
                    queue.add(tmp.right);
                    nextLevel++;
                }
                toBePrinted--;
                if(toBePrinted==0)
                {
                    re.add(cuLevel);
                    cuLevel = new ArrayList<>();
                    toBePrinted = nextLevel;
                    nextLevel=0;
                }
    
            }
            return re;
        }
    }
    

      

  • 相关阅读:
    马哥Linux——第三周作业
    [laravel]phpunit
    [laravel]要点
    [laravel]请求处理
    [angularJS]ng-hide|ng-show切换
    [yii2]urlmanger
    虚拟机bridged, NAT and host-only网络区别
    [yii]Fetch data from database and create listbox in yii
    [shell test] multiple conditions
    特殊的shell变量:
  • 原文地址:https://www.cnblogs.com/MrSaver/p/9321112.html
Copyright © 2011-2022 走看看