剑指offer_23

本文介绍了一种使用队列实现的二叉树层序打印算法。通过将二叉树节点逐层加入队列并依次打印,实现了从上至下、从左至右的遍历。文中提供了一个具体的Java实现案例。

题意:层序打印二叉树
思路:维护一个队列,存储二叉树从上至下、从左至右的打印顺序,先进先出。
代码:

package MianShiTi_23;

import java.util.LinkedList;
import java.util.Queue;

import javax.swing.text.AbstractDocument.LeafElement;

public class MianShiTi_23 {
    public static class binaryTree {
        int value;
        binaryTree leftChild;
        binaryTree rightChild;
    }
    public static void layerTraversal(binaryTree node) {
        if(node == null){return;}
        //linkedlist实现了queue。
        Queue<binaryTree> queue = new LinkedList<>();
        queue.add(node);
        while (queue.size() != 0) {
            binaryTree pnode = queue.poll();
            System.out.print(pnode.value+"->");
            if(pnode.leftChild != null){
                queue.add(pnode.leftChild);
            }
            if(pnode.rightChild != null){
                queue.add(pnode.rightChild);
            }
        }

    }
    public static void main(String[] args) {
        binaryTree node = new binaryTree();
        node.value = 8;
        node.leftChild = new binaryTree();
        node.leftChild.value = 6;
        node.rightChild = new binaryTree();
        node.rightChild.value = 10;
        node.leftChild.leftChild = new binaryTree();
        node.leftChild.leftChild.value = 5;
        node.leftChild.rightChild = new binaryTree();
        node.leftChild.rightChild.value = 7;
        node.rightChild.leftChild = new binaryTree();
        node.rightChild.leftChild.value = 9;
        node.rightChild.rightChild = new binaryTree();
        node.rightChild.rightChild.value = 11;
        new MianShiTi_23().layerTraversal(node);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值