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

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

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

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);
				
			}
		}
		
	}
}
    原文作者:B树
    原文地址: https://blog.csdn.net/A784586/article/details/62042814
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞