二叉树层次序遍历

//二叉树的层次序遍历
	public void Level(TreeNode r){
		//定义一个队列
		MyQueue<TreeNode> queue=new MyQueue<TreeNode>();
		queue.enQueue(r);
		while(!queue.isEmpty()){
			TreeNode tmp=queue.getFront();
			queue.deQueue();
			System.out.print(tmp.data+" ");
			if(tmp.lChild!=null)
				queue.enQueue(tmp.lChild);
			if(tmp.rChild!=null)
				queue.enQueue(tmp.rChild);
		}
	}
/*
	 * 结点类 成员变量:结点中数据data,左孩子lChild,右孩子结点rChild.
	 */
	class TreeNode {
		private char data;
		private TreeNode lChild;
		private TreeNode rChild;

		public TreeNode(char d) {
			data = d;
			lChild = null;
			rChild = null;
		}

		public TreeNode(char d, TreeNode l, TreeNode r) {
			data = d;
			lChild = l;
			rChild = r;
		}
	}
package com.zhiru;
import java.util.LinkedList;
//用LinkedList实现队列.

//fifo
public class MyQueue<E> {
	private LinkedList<E> s = new LinkedList<E>();
	public void enQueue(E e){
		s.offer(e);
	}
	public E deQueue(){
		return s.poll();
	}
	public E getFront(){
		return s.peek();
	}
	public boolean isEmpty(){
		return s.isEmpty();
	}
	public int size(){
		return s.size();
	}
	public String toString(){
		return s.toString();
	}
}



你可能感兴趣的:(二叉树,层次序遍历)