树的层次遍历【队列的应用】

树的层次遍历【队列的应用】

思想:将不空的根节点入队列,队列不空的时候出队列,访问该节点,然后分别将左右孩子入队列,正好先出左,再出右,跟队列契合。


java实现代码;

package com.mytest.mymain;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
class BTree{
	public int value;  //public static int value;  那么最终输出都为8个8
	public BTree left;  
	public BTree right;  
	BTree(int x) { value = x; }  
}
public class TraversalTree {
	public static void main(String[] args) {
		BTree root=new BTree(1);
		BTree Node2=new BTree(2);
		BTree Node3=new BTree(3);
		BTree Node4=new BTree(4);
		BTree Node5=new BTree(5);
		BTree Node6=new BTree(6);
		BTree Node7=new BTree(7);
		BTree Node8=new BTree(8);
	
		root.left=Node2;
		root.right=Node3;
		
		Node2.left=Node4;
		Node2.right=Node5;
		
		Node3.left=Node6;
		Node3.right=Node7;
		
		Node4.left=Node8;
		
		System.out.println("层次遍历");
		levelorder(root);
	}
	//层次遍历
	public static void levelorder(BTree root){
		Queue<BTree> queue=new LinkedList<BTree>();
		BTree bTree=null;
		
		if(root != null){
			queue.add(root);
		}
		
		while(!queue.isEmpty()){
			bTree=queue.poll();
			System.out.print(bTree.value+"  ");
			if(bTree.left != null){
				queue.add(bTree.left);
			}
			if(bTree.right !=null ){
				queue.add(bTree.right);
				
			}
		}
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值