#二叉树层序遍历 #层序遍历并返回list

本文介绍了如何进行二叉树的层序遍历,重点是利用队列的先进先出特性,自顶向下或自底向上逐层遍历并打印二叉树节点。同时,提供了在层序遍历过程中返回二维List的方法。

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

层序遍历:即把一颗二叉树从上到下,从左到右遍历并打印

这里我们可以想到用队列,先放进去的先出来,把二叉树的每一层都依次保存到队列中

public class BinaryTree {
    public static class BTNode {
        //定义属性
        public BTNode left;
        public BTNode right;
        int val;

        public BTNode(int val) {
            this.val = val;
        }

        public BTNode(BTNode left, BTNode right, int val) {
            this.left = left;
            this.right = right;
            this.val = val;
        }
    }
    BTNode root;//指向根结点

    //创建一棵树void creatTree() {
        BTNode node1 = new BTNode(11);
        BTNode node2 = new BTNode(22);
        BTNode node3 = new BTNode(33);
        BTNode node4 = new BTNode(44);
        BTNode node5 = new BTNode(55);
        BTNode node6 = new BTNode(66);

        node1.left = node2;
        node1.right = node4;

        node2.left = node3;

        node4.left = node5;
        node4.right = node6;
        root=node1;
    }

//层序遍历
public void levelorder(){
    if(root==null){
        return ;
    }
    Queue<BTNode> s=new LinkedList<>();
    s.offer(root);
   while(!s.isEmpty()){
       BTNode cur=s.poll();
       System.out.print(cur.val+" ");
       if(cur.left!=null){
           s.offer(cur.left);
       }
       if(cur.right!=null){
           s.offer(cur.right);
       }
   }
}

  public static void main(String[] args) {
      BinaryTree bt=new BinaryTree();
        System.out.println("============================");
        System.out.println("层序遍历:");
        bt.levelorder();
    }
}


#二叉树的层序遍历, 返回二维List(题目描述如下)

和上道题本质一样,不同之处在于,这里要求从从下到上输出每一层的节点值。

除了输出顺序不同以外,这两道题的思路是相同的,

public void levelOder() {  //公共的,没有参数,好调用
    List<List<Integer>> as=levelOder(root);
    System.out.println(as);
}
private List<List<Integer>> levelOder(BTNode root){
    List<List<Integer>> list = new ArrayList<>();
    //(1)为空时返回[],即创建的空数组if(root==null){
        return list;
    }
    //(2)用队列循环保存每一层,并存在数组里Queue<BTNode> s = new LinkedList<>();
    s.offer(root);
    while(!s.isEmpty()){
        int levelsize=s.size();
        //创建新数组,即内部数组List<Integer> levelVal=new ArrayList<>();
        for(int i=0;i<levelsize;i++){
            BTNode cur=s.poll();
            levelVal.add(cur.val);//把队列中存的元素拿到数组中保存//循环遍历左右字数if(cur.left!=null){
                s.offer(cur.left);
            }
            if(cur.right!=null){
                s.offer(cur.right);
            }
        }
        list.add(levelVal);//把内部数组存放到外面那个大数组中
    }
    return list;//返回数组
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值