package com.vic.tree;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* 层次遍历二叉树
* @author Administrator
*
*/
public class BFSTree {
static void BFS(BinaryTree root){
if(root==null)
return;
Queue<BinaryTree> queue = new LinkedList<BinaryTree>();
queue.add(root);
while(!queue.isEmpty()){
BinaryTree tempTree = queue.poll();
System.out.print(tempTree.data+" ");
if(tempTree.left!=null)
queue.add(tempTree.left);
if(tempTree.right!=null)
queue.add(tempTree.right);
}
}
/**
* 先序创建二叉树
* @return
*/
static BinaryTree createTree(){
Scanner sc = new Scanner(System.in);
int flag = sc.nextInt();
if(flag==0)
return null;
BinaryTree root = new BinaryTree(flag);
root.left = createTree();
root.right = createTree();
return root;
}
public static void main(String[] args) {
System.out.println("建立二叉树,输入0结束:");
BinaryTree root = createTree();
System.out.println("建立完毕");
BFS(root);
}
}
class BinaryTree{
int data;
BinaryTree left;
BinaryTree right;
BinaryTree() {
}
BinaryTree(int data) {
this.data = data;
}
}
二叉树的层次遍历
最新推荐文章于 2024-09-08 20:07:18 发布