二叉树按层遍历

一、非递归方法,使用一个队列保存访问过的元素

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author:fangxuan
 * @date:2015年10月13日
 * @description:
 */
public class BinaryTree {

    private static final int[] data = {1,2,3,4,5,6,7}; 
    private static int index=0;
    private Queue<Node> queue = new ArrayBlockingQueue<Node>(10);
    public Node root;

    /**
     * 按层创建二叉树,完全二叉树
     */
    private void create(){
        if(index>=data.length)
            return;

        // 根结点
        if(root == null){
            root = new Node();
            root.value = data[index++];
        }
        queue.add(root);
        while(!queue.isEmpty()){
            if(index>=data.length)
                return;

            Node n = queue.poll();
            // 左孩子
            n.left = new Node();
            n.left.value=data[index++];
            queue.add(n.left);

            if(index>=data.length)
                return;
            // 右孩子
            n.right = new Node();
            n.right.value=data[index++];
            queue.add(n.right);
        }
    }
    /**
     * 按层遍历
     */
    public void levelTraverse(){
        if(root==null)
            return;
        Queue<Node> q = new ArrayBlockingQueue<Node>(10);
        System.out.print(root.value+" ");
        q.add(root);

        while(!q.isEmpty()){
            Node n = q.poll();
            if(n.left!=null){
                System.out.print(n.left.value+" ");
                q.add(n.left);
            }
            if(n.right!=null){
                System.out.print(n.right.value+" ");
                q.add(n.right);
            }
        }
    }


    /**
     * 先序遍历
     */
    public void preOrder(){
        preOrder(root);
    }
    /**
     * 先序遍历的递归算法
     * @param root
     */
    private void preOrder(Node root){
        if(root == null)
            return;
        System.out.print(root.value+" ");

        preOrder(root.left);
        preOrder(root.right);
    }

    public static void main(String[] args){
        BinaryTree tree = new BinaryTree();
        tree.create();
        tree.preOrder();
        System.out.println();
        tree.levelTraverse();
    }
}

class Node {
    public int value;
    public Node left;
    public Node right;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值