zoukankan      html  css  js  c++  java
  • [编程题] 把二叉树打印成多行

    把二叉树打印成多行

    题目描述

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

    image-20200625195832301

    思考分析(类似二叉树的程序遍历)

    参考:二叉树层序遍历

    要把二叉树按照每行打印出来,我们可以借助一个队列来处理,一开始把root节点放入到对列中,每次处理,把队列中的元素取出,放入到一个行中(list),然后把队列中的所有信息都换为其下一行的孩子信息,继续如上处理.直至某一次队列返回空,就跳出while循环,返回结果。

    Java代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
       
        public List<List<Integer>> levelOrder(TreeNode pRoot) {
            Queue<TreeNode> queue = new LinkedList(); //处理队列
            
            ArrayList  res = new ArrayList(); //结果集合
            if(pRoot==null) return new ArrayList();
            
            //把root放入队列
            if(pRoot!=null){
                queue.offer(pRoot);
            }
            
            //队不为空时处理
            while(!queue.isEmpty()){
                //把队列中的每个元素放入这行的list
                ArrayList line = new ArrayList();
                //调用change函数,把对中元素换为其下一行的其孩子们
                Queue<TreeNode> temp = change(queue,line,res);
                queue = temp;//把temp队列赋值给queue队列
            }
            
             //如果queue为空了,就结束了
            return res;
        }
        
        //取出传入的queue的所有元素,放入了行集合,也把queu中元素的子节点放入了temp队列中返回
        public Queue<TreeNode> change(Queue<TreeNode> queue,ArrayList line,ArrayList res){
            Queue<TreeNode> temp = new LinkedList();  //临时存储
            while(!queue.isEmpty()){
                TreeNode node = queue.poll();
                line.add(node.val);//放入本行的集合中
                //把其子放入到temp队列中
                if(node.left!=null){
                    temp.offer(node.left);
                }
                if(node.right!=null){
                    temp.offer(node.right);
                }
            }
            res.add(line);//把本行的结果放入总结果集合
            //取完了queue的所有元素,放入了行中,也把queu中元素的子放入了temp队列中了,返回
            return temp;
        }
    }
    

    测试输出:

    image-20200625200221573

  • 相关阅读:
    linux编译C
    Windows下ARP协议的工作原理简介
    窥探QQ基础数据库架构演变史
    JAVA培训—线程同步--卖票问题
    SQLite、MySQL和PostgreSQL 三种关系数据库哪个好?
    再论谭浩强《C语言程序设计》
    JPG加入RAR文件原理详解
    如何区分一个程序员是“老手“还是“新手“?
    AutoITx3.DLL所有函数及说明
    windows索引服务
  • 原文地址:https://www.cnblogs.com/jiyongjia/p/13192784.html
Copyright © 2011-2022 走看看