剑指offer:把二叉树打印成多行

博客围绕从上到下按层打印二叉树且每层一行的问题展开。对比相关二叉树打印题目,指出广度优先遍历需用队列,先将根节点入队,取出节点后将其子节点入队。还给出两种实现思路,一是用队列存储,记录每层节点数完成打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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

 

思路:

对比从上到下打印二叉树https://blog.youkuaiyun.com/orangefly0214/article/details/83743664

以及上一个题目:按之字形顺序打印二叉树https://blog.youkuaiyun.com/orangefly0214/article/details/87907869

不管是广度优先遍历有向图还是一棵树,都需要用到队列。首先将根节点放入队列,接下来每次从队列头部取出一个节点,遍历这个节点之后把它能到达的子节点都依次放入队列。重复这个过程,直到队列中的所有节点全部被遍历为止。

实现1:

和二叉树的深度的广度优先遍历一样,用队列存储,每层打印之前,记录size得到该层节点数,完成每一层的打印。

public class Solution {
    ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> ret=new ArrayList<ArrayList<Integer>>();
        if(pRoot==null) return ret;
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        queue.offer(pRoot);
        while(!queue.isEmpty()){
            ArrayList<Integer> sub=new ArrayList<Integer>();
            int size=queue.size();
            for(int i=0;i<size;i++){
                TreeNode node=queue.poll();
                sub.add(node.val);
                if(node.left!=null){
                    queue.offer(node.left);
                }
                if(node.right!=null){
                    queue.offer(node.right);
                }
            }
            if(!sub.isEmpty()){
                ret.add(sub);
            }
        }
        return ret;
    }   
}

实现2:

import java.util.ArrayList;
 
 
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> ret=new ArrayList<ArrayList<Integer>>();
         if(pRoot==null){
             return null;
         }
         Queue<TreeNode> queue=new LinkedList<TreeNode>();
         queue.add(pRoot);
         int toBePrinted=1;
         int nextLine=0;
         ArrayList<Integer> sublist=new ArrayList<>();
         while(!queue.isEmpty()){
             TreeNode curr=queue.poll();
             sublist.add(curr.val);
             --toBePrinted;
             if(curr.left!=null){
                 queue.add(curr.left);
                 ++nextLine;
             }
             if(curr.right!=null){
                 queue.add(curr.right);
                 ++nextLine;
             }
             if(toBePrinted==0){
                 ret.add(sublist);
                 sublist=new ArrayList<>();
                 toBePrinted=nextLine;
                 nextLine=0;
             }
         }
        return ret;
     
    }
     
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值